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




posted @   czcb  阅读(306)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示