1、变量

  1. $price = 11.0;
  2. $name = "lisi";
  3. $var = "hello"."world"; # "helloworld" 字符串连接
  4. $name = "i am $name " # "i am lisi " #变量内插
  5. # 没有布尔数据类型, 数字0为假,非0为真,非空字符串为真,除了"0",这个会转换为数字0,所以为假

1.1、哈希

  1. my $hash=(
  2. a => 1,
  3. b => 2,
  4. c => "sdf",
  5. );
  6. my @k = keys %hash;
  7. my @v = values %hash;
  1. #!/usr/bin/perl
  2. print "PATH is $ENV{PATH}\n";
  3. print "while循环,取出键值对\n";
  4. while (($key,$value)=each %ENV){
  5. print "$key => $value\n";
  6. }
  7. print "foreach 循环,取出键,通过键获取值\n";
  8. foreach $key (keys %ENV){
  9. print "$key => $ENV{$key}\n";
  10. }

2、程序结构

2.1、分支

  1. #!/usr/bin/perl
  2. $line = <STDIN>;
  3. if($line eq "\n"){
  4. print "That was just a blank line !\n";
  5. } else {
  6. print "That line of input was :$line";
  7. }

2.2、循环

  1. #!/usr/bin/perl
  2. $count = 0 ;
  3. while($count < 10){
  4. $count +=2;
  5. print "count is now $count\n";
  6. }

3、函数

3.1、去除末尾换行符

  1. chomp($text);
  2. chomp $text
  3. chomp($text=<STDIN>);
  4. # 结尾有多个换行符,也仅仅删除一个,如果没有,它什么也不做,直接返回0.返回值为删除的字符数。

3.2、输入

  1. $line = <STDIN>;

4、子程序

  1. #!/usr/bin/perl
  2. use strict;
  3. sub total {
  4. my $sum = 0;
  5. foreach my $num (@_){
  6. print "$num\n";
  7. $sum += $num;
  8. }
  9. print "$sum\n";
  10. return $sum;
  11. }
  12. my @fred = 1..100;
  13. my $fred_total = total(@fred);
  14. print "The total of \@fred is $fred_total.\n";
  1. use strict;
  2. sub avg {
  3. my $sum = 0;
  4. foreach my $num (@_){ # @_表示参数列表
  5. $sum += $num;
  6. }
  7. print "$sum\n";
  8. return $sum/@_;
  9. }
  10. above_average(1..100);
  11. sub above_average {
  12. my $avg_num = avg(@_);
  13. my @list;
  14. foreach (@_){
  15. if ($_ > $avg_num){ # 循环的控制变量默认为$_
  16. push @list , $_ ;
  17. }
  18. }
  19. print "@list\n";
  20. }
  21. above_average(2,2,4,5);
  1. #!/usr/bin/perl
  2. use 5.010;
  3. sub greet {
  4. state $last_person; # 持久的私有变量
  5. my $name = shift;
  6. print "Hi $name!\n";
  7. if(defined $last_person){
  8. print "$last_person is also here!\n";
  9. }else{
  10. print "You are the first one here\n";
  11. }
  12. $last_person=$name;
  13. }
  14. greet("lisi");
  15. greet("sss");