有时候在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, yes, an $input is an animal!\n";
last;
}
} finally {
print "Sorry, I'm not sure if $input is an animal or not\n";
}
这将使得测试更加直观易懂。
first
。 - chorobaif(grep(/$input/, @animals)){ true clause } else { equivalent of finally }
- dawg