有时在Perl中,我编写了一个for / foreach循环,它迭代值以检查列表中的值.在第一次击中之后,循环可以退出,因为我们已经满足了我的测试条件.例如,这个简单的代码:
my @animals = qw/cat dog horse/; foreach my $animal (@animals) { if ($input eq $animal) { print "Ah,yes,an $input is an animal!\n"; last; } } # <-----
是否有一种优雅的方式 – 可能是一个重载的关键字 – 来处理“for循环到达最后一个元素”?什么东西放在上面的箭头?
我可以想办法做到这一点,比如创建/设置一个额外的$found变量并在最后测试它……但是我希望Perl可能还有其他内置的东西,比如:
foreach my $animal (@animals) { if ($input eq $animal) { print "Ah,an $input is an animal!\n"; last; } } finally { print "Sorry,I'm not sure if $input is an animal or not\n"; }
这将使这个测试更直观.
解决方法
您可以使用带标签的块包装循环,如下所示:
outer: { foreach my $animal (@animals) { if ($input eq $animal) { print "Ah,an $input is an animal!\n"; last outer; } } print "no animal found\n"; }