1、perl的语句都类似 CIf ( ) elsewhile ( ) for ($count=1; $count );if ($a=5) print “ok“;macglocalhost perltest$ ./tip.plsyntax error at ./tip.pl line 7, near “) print“Execution of ./tip.pl aborted due to compilation errors. if ( ) elsif ( ) else 注意:是 elsif不是 elseif until循环until ( ) foreach 针对数组每个元素的循环#!/usr/b
2、in/perltmp=qw(aaa bbb kkk 9000);$i=0;foreach $tt(tmp) print “no.$i is $tt“,“n“;$i+; #!/usr/bin/perltmp=qw(aaa bbb kkk 9000);for($i=0;$i) print “no.$i =“;$i+;if($input eq “q“) print “choose q n“;last;elsif ($input eq n) print “choose n next:“;next;elsif ($input eq r) print “redo :“;redo;else print “i
3、nput ok n“;print “input:“; macglocalhost perltest$ ./tip.plinput:xno.1 =input okinput:nno.2 =choose n next:w next语句直接循环结束,所以没执行 print “input:“;no.3 =input okinput:qno.4 =choose q last, 循环结束redo造成死循环的原因while(chomp($input=) print “no.$i =“;$i+;if($input eq “q“) print “choose q n“;last;elsif ($input eq
4、 n) print “choose n next:“;next;elsif ($input eq r) print “redo :“;redo;else print “input ok n“;print “input:“; macglocalhost perltest$ ./tip.plinput:r:no.2228 =redo :no.2229 =redo :no.2230 =redo :no.2241 =redo :no.2242 =redo :no.2243 =redo :no.2244 =redo :no.2245 =redo :no.2246 =redo :no.2247 =redo
5、 :no.2248 =redo :no.2249 =redo :no.2250 =redo :no.2251 =redo :no.2252 =redo :no.2253 =redo :no.2254 =redo :no.2255 =redo :no.2256 =redo :no.2257 改成 for循环,并把 chomp($input=);移到循环体内 #!/usr/bin/perlfor($i=1;$i“;chomp($input=);if($input eq “q“) print “choose q n“;last;elsif ($input eq n) print “choose n
6、n“;next;elsif ($input eq r) print “redo n“;redo;print “input ok n“; macglocalhost perltest$ ./tip.plno.1 =xinput okno.2 =sinput okno.3 =rredono.3 =nchoose nno.4 =qchoose q 结论:redo会取消循环大括号内到 redo前的所有语句,然后再重新执行这些语句但不重新执行循环语句里面的循环判定语句,如 while(chomp($input=),即 redo只在循环体内转所以使用 redo时,循环判定语句里尽量只放条件判断表达式,不要
7、放执行语句。传统的 goto label;unless语句 if 语句的反义词if 是判斷條件為真時做某事,unless 剛好相反unless (條件判斷為假) 做某些事情 else 做另一些事情 perl 也支持 switch,但必须 use模块#!/usr/bin/perl -wuse Switch;print“input:“;$i=1;while(chomp($input=) print “no.$i =“;switch ( $input) case 1 print “is number 1“; case 2 print “is number 2“; else print “must b
8、e 1 or 2“; exit 0;$i+;print “input:“;macnm testpl$ ./testpl.plinput:1no.1 =is number 1input:2no.2 =is number 2input:3no.3 =must be 1 or 2=简化语句=简化 if语句-三元運算#!/usr/bin/perlchomp($j= $b) ? $a : $b; en(W, “ $log“) | die “$!n“; 最常用等价于 if ( ! open(W, “ $log“) print “$!n“; print “ the file $file is existn“ if (-e $file);#!/usr/bin/perlchomp($file=);print “ the file $file is existn“ if (-e $file);macglocalhost perltest$ lsgogo tip.plmacglocalhost perltest$ ./tip.pltip.plthe file tip.pl is existunlink $filename if -e $filename; 等价于 if (-e $filename) unlink $filename;command; while(条件表达式); 一句话循环