cat 123.txt | perl -n -a -F"\s+" -e ' if($F[2] >= 80){ $n += 1; }else{ $m += 1; } END{ print "the number of upper 80 score : $n !\n"; print "the number of lower 80 score : $n !\n"; } ' ----------------------------- # 输出为 the number of upper 80 score : 4 ! the number of lower 80 score : 6 !
结果正确,但是如果这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
cat 123.txt | perl -n -a -F"\s+" -e ' my ($n,$m); if($F[2] >= 80){ $n += 1; }else{ $m += 1; } END{ print "the number of upper 80 score : $n !\n"; print "the number of lower 80 score : $n !\n"; } ' ----------------------------- # 输出为 the number of upper 80 score : 1 ! the number of lower 80 score : 1 !
| # perl script | # perl one-liners use strict; | perl -Mstrict use warnings; | perl -Mwarnings | BEGIN{ | # 这里不能使用my声明,如果使用my声明的话,出了BEGIN块,这两个变量就失效了 our ($n,$m); | our ($n,$m); | } open FILE,"<","123.txt" or die $!; | # 其实在说-e参数的时候就已经说过,除了BEGIN与END块之外,perl的代码块其实是处在类似于whlie(<FILE>)的循环之中 while(<FILE>){ | cat 123.txt | | # 仍然在our的作用范围之内 | # 出了BEGIN代码块,这里需要再次指明使用这两个变量 | our ($n,$m); my @F = split /\s+/,$_; | if($F[2] >= 80){ | if($F[2] >= 80){ $n += 1; | $n += 1; }else{ | }else{ $m += 1; | $m += 1; } | } } | | END{ print"the number of upper 80 score : $n !\n"; | print"the number of upper 80 score : $n !\n"; print"the number of lower 80 score : $n !\n"; | print"the number of lower 80 score : $n !\n"; | }
也许你会这么写:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
perl -e ' use strict; use warnings; my ($n,$m); open FILE,"<","123.txt" or die $!; while(<FILE>){ my @F = split /\s+/,$_; if($F[2] >= 80){ $n += 1; }else{ $m += 1; } } print "the number of upper 80 score : $n !\n"; print "the number of lower 80 score : $n !\n"; '