How do I break out of a loop in Perl?

时光毁灭记忆、已成空白 提交于 2019-11-26 17:55:14

问题


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:

Bareword "break" not allowed while "strict subs" in use at ./final.pl line 154.

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:


Oh, I found it. You use last instead of break

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



回答2:


Additional data (in case you have more questions):

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

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



回答3:


Simply last would work here:

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

If you have nested loops, then last will exit from the innermost. 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. Same can be done in any number of loops, and labels can be fixed anywhere.




回答4:


On a large iteration I like using interrupts. Just press Ctrl + C to quit:

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

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


来源:https://stackoverflow.com/questions/303216/how-do-i-break-out-of-a-loop-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!