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;
}
}
Additional data (in case you have more questions):
FOO: {
for my $i ( @listone ){
for my $j ( @listtwo ){
if ( cond( $i,$j ) ){
last FOO; # --->
# |
} # |
} # |
} # |
} # <-------------------------------
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.
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