perl next和last

跳出控制結構:next和last


next 和last 操做符運維你在循環中改變程序執行的方向,你可能常常會遇到一些的特殊狀況,

碰到這種狀況時你但願跳過它,或者像退出循環。

好比當你處理Unix 帳號時,你也許但願跳過系統帳號(好比root或Ip),

next 操做符容許你將跳至本地循環的結束,

開始下一個循環。


而last 操做符容許你跳至整個循環的結束,若是循環條件表達式爲假時發生的狀況同樣。



next 跳過本地循環,回到循環頂端:
Vsftp:/data01/mysqllog/binlog# cat a3.pl 
my @users=qw/root a1 a2 a3 b1 b2 b3 lp c1 c2 c3/;
 foreach $user (@users){
   if ($user eq "root" or $user eq "lp") {next;};
   print "\$user is $user\n";
   }
Vsftp:/data01/mysqllog/binlog# perl a3.pl 
$user is a1
$user is a2
$user is a3
$user is b1
$user is b2
$user is b3
$user is c1
$user is c2
$user is c3


last 退出循環:

Vsftp:/data01/mysqllog/binlog# cat a3.pl 
my @users=qw/ a1 a2 a3 b1 root b2 b3 lp c1 c2 c3/;
 foreach $user (@users){
   if ($user eq "root" or $user eq "lp") {last;};
   print "\$user is $user\n";
   }
Vsftp:/data01/mysqllog/binlog# perl a3.pl 
$user is a1
$user is a2
$user is a3
$user is b1



例子:next 跳過本次循環

Vsftp:/data01/mysqllog/binlog# cat t2.pl 
my $str='AAWHEREBBCC';
 if ($str =~ s/WHERE/SET/)
   {print "\$str---1 is $str\n"}
elsif ($str=~ s/SET/SCAN/)
   {print "\$str---2 is $str\n";};

Vsftp:/data01/mysqllog/binlog# perl t2.pl 
$str---1 is AASETBBCC



相關文章
相關標籤/搜索