首页 > 代码库 > Perl 学习笔记

Perl 学习笔记

Note I:子程序的基本应用1

技术分享
 1 #!/usr/bin/perl -w
 2 
 3 use 5.018;
 4 
 5 sub total
 6 {
 7     my $res;
 8     foreach (@_)
 9     {
10         $res += $_;
11     }
12     $res;
13 }
14 
15 my @list;
16 my $cur;
17 while ($cur = <STDIN>)
18 {
19     chomp $cur;
20     push @list, $cur;
21 }
22 my $sum;
23 $sum = &total (@list);
24 say "The sum is $sum";
Exercise I

Note II:子程序的基本应用2

print "@list";一句使用了数组的双引号内插,这样打印出的元素之间会用空格分开。如果去掉双引号,那么数组中的所有元素都会挤在一起。

技术分享
 1 #!/usr/bin/perl -w
 2 
 3 use 5.018;
 4 
 5 sub above_average
 6 {
 7     my $aver;
 8     foreach (@_)
 9     {
10         $aver += $_;
11     }
12     $aver /= @_;
13     my @res;
14     foreach (@_)
15     {
16         if ($_ > $aver)
17         {
18             push @res, $_;
19         }
20     }
21     @res;
22 }
23 
24 my @list = &above_average (200, 1..100);
25 print "@list";
Exercise II

Note III:子程序的基本应用3

这里用到了state关键字(类似于C语言的static)。

这里我起初犯了个错误:把my ($cur) = @_; 写成了my $cur = $_; 。参数会默认存放在@_数组中,即使参数只有一个。

技术分享
 1 #!/usr/bin/perl -w
 2 
 3 use 5.018;
 4 
 5 sub greet
 6 {
 7     state @list;
 8     my ($cur) = @_;
 9     print "Hi $cur! I‘ve seen: @list\n";
10     push @list, $cur;
11 }
12 
13 my $cur;
14 while ($cur = <STDIN>)
15 {
16     chomp $cur;
17     &greet ($cur);
18 }
Exercise III

Note IV:简单的输入输出1

注意chomp!

技术分享
 1 #!/usr/bin/perl
 2 
 3 use 5.018;
 4 
 5 print "1234567890" x 5 . "\n";
 6 while (<STDIN>)
 7 {
 8     chomp $_;
 9     printf "%20s", $_;
10 }
Exercise IV

Note V:简单的输入输出2

代码中提到的两种写法都是可行的

(顺便吐槽一下Perl居然不支持注释块,还好有Vim帮忙……)

技术分享
 1 #!/usr/bin/perl
 2 
 3 use 5.018;
 4 
 5 chomp (my $width = <STDIN>);
 6 foreach (1..$width)
 7 {
 8     print $_ % 10;
 9 }
10 print "\n";
11 
12 #while(<STDIN>)
13 #{
14 #    chomp $_;
15 #    printf "%${width}s\n",$_;
16 #}
17 while (chomp (my $line = <STDIN>) )
18 {
19     printf "%${width}s\n", $line;
20 }
21 #These two ways are both OK.
Exercise V

Note VI:哈希的应用1,each遍历整个哈希

(内置Hash就是吼啊~)

另外,while (chomp (my $line = <STDIN>) )一句,结束输入时$line为undef,这时用chomp处理的话Perl会提出警告,不过目前来看并无大碍(但愿吧)

技术分享
 1 #!/usr/bin/perl -w
 2 
 3 use 5.018;
 4 
 5 my % hash;
 6 while (chomp (my $line = <STDIN>) ) #warning
 7     {
 8         my ($first, $last) = split /\s+/, $line;
 9         $hash{$first} = $last;
10     }
11     printf "%20s%20s\n", "First Name", "Last Name";
12 while (my ($first, $last) = each % hash)
13 {
14     printf "%20s%20s\n", $first, $last;
15 }
Exercise VI

Note VII:哈希的应用2

技术分享
 1 #!/usr/bin/perl -w
 2 
 3 use 5.018;
 4 
 5 my %cnt;
 6 while (my $line = <STDIN>)
 7 {
 8     chomp $line;
 9     ++$cnt{$line};
10 }
11 while (my ($word, $n) = each % cnt)
12 {
13     print "$word => $n\n";
14 }
Exercise VII

 

To be continued...

Perl 学习笔记