本文翻译自: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. 可以在任意数量的循环中完成相同的操作,并且标签可以在任何地方固定。