1、变量
$price = 11.0;
$name = "lisi";
$var = "hello"."world"; # "helloworld" 字符串连接
$name = "i am $name " # "i am lisi " #变量内插
# 没有布尔数据类型, 数字0为假,非0为真,非空字符串为真,除了"0",这个会转换为数字0,所以为假
1.1、哈希
my $hash=(
a => 1,
b => 2,
c => "sdf",
);
my @k = keys %hash;
my @v = values %hash;
#!/usr/bin/perl
print "PATH is $ENV{PATH}\n";
print "while循环,取出键值对\n";
while (($key,$value)=each %ENV){
print "$key => $value\n";
}
print "foreach 循环,取出键,通过键获取值\n";
foreach $key (keys %ENV){
print "$key => $ENV{$key}\n";
}
2、程序结构
2.1、分支
#!/usr/bin/perl
$line = <STDIN>;
if($line eq "\n"){
print "That was just a blank line !\n";
} else {
print "That line of input was :$line";
}
2.2、循环
#!/usr/bin/perl
$count = 0 ;
while($count < 10){
$count +=2;
print "count is now $count\n";
}
3、函数
3.1、去除末尾换行符
chomp($text);
chomp $text
chomp($text=<STDIN>);
# 结尾有多个换行符,也仅仅删除一个,如果没有,它什么也不做,直接返回0.返回值为删除的字符数。
3.2、输入
$line = <STDIN>;
4、子程序
#!/usr/bin/perl
use strict;
sub total {
my $sum = 0;
foreach my $num (@_){
print "$num\n";
$sum += $num;
}
print "$sum\n";
return $sum;
}
my @fred = 1..100;
my $fred_total = total(@fred);
print "The total of \@fred is $fred_total.\n";
use strict;
sub avg {
my $sum = 0;
foreach my $num (@_){ # @_表示参数列表
$sum += $num;
}
print "$sum\n";
return $sum/@_;
}
above_average(1..100);
sub above_average {
my $avg_num = avg(@_);
my @list;
foreach (@_){
if ($_ > $avg_num){ # 循环的控制变量默认为$_
push @list , $_ ;
}
}
print "@list\n";
}
above_average(2,2,4,5);
#!/usr/bin/perl
use 5.010;
sub greet {
state $last_person; # 持久的私有变量
my $name = shift;
print "Hi $name!\n";
if(defined $last_person){
print "$last_person is also here!\n";
}else{
print "You are the first one here\n";
}
$last_person=$name;
}
greet("lisi");
greet("sss");