如何在Perl中打破循环?

本文翻译自:How do I break out of a loop in Perl?

I'm trying to use a break statement in a for loop, but since I'm also using strict subs in my Perl code, I'm getting an error saying: 我试图在for循环中使用break语句,但由于我在Perl代码中也使用了严格的subs,我收到一个错误说:

Bareword "break" not allowed while "strict subs" in use at ./final.pl line 154. 在./final.pl第154行使用“严格潜艇”时不允许使用Bareword“break”。

Is there a workaround for this (besides disabling strict subs)? 有没有解决方法(除了禁用严格的潜艇)?

My code is formatted as follows: 我的代码格式如下:

for my $entry (@array){
    if ($string eq "text"){
         break;
    }
}

#1楼

参考:https://stackoom.com/question/1gSA/如何在Perl中打破循环


#2楼

Oh, I found it. 哦,我找到了。 You use last instead of break 你使用last而不是break

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

#3楼

Additional data (in case you have more questions): 其他数据(如果您有更多问题):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

#4楼

On a large iteration I like using interrupts. 在大型迭代中,我喜欢使用中断。 Just press Ctrl + C to quit: 只需按Ctrl + C退出:

my $exitflag = 0;
$SIG{INT} = sub { $exitflag=1 };

while(!$exitflag) {
    # Do your stuff
}

#5楼

Simply last would work here: last可以在这里工作:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

If you have nested loops, then last will exit from the innermost. 如果你有嵌套循环,那么last将退出最里面。 Use labels in this case: 在这种情况下使用标签:

LBL_SCORE: {
       for my $entry1 ( @array1 ){
          for my $entry2 ( @array2 ){
                 if ( $entry1 eq $entry2 ){   # or any condition
                    last LBL_SCORE;
                 }
          }
       }
 }

Given last statement will make compiler to come out from both the loops. 鉴于last语句将使编译器从两个循环中出来。 Same can be done in any number of loops, and labels can be fixed anywhere. 可以在任意数量的循环中完成相同的操作,并且标签可以在任何地方固定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值