How do I break out of a loop in Perl?

2020-01-29 03:28发布

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;
    }
}

4条回答
一纸荒年 Trace。
2楼-- · 2020-01-29 03:45

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.

查看更多
走好不送
3楼-- · 2020-01-29 03:48

Additional data (in case you have more questions):

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

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------
查看更多
我欲成王,谁敢阻挡
4楼-- · 2020-01-29 03:48

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
}
查看更多
做个烂人
5楼-- · 2020-01-29 03:51

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

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}
查看更多
登录 后发表回答