【发布时间】:2018-12-21 22:31:27
【问题描述】:
有时在 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";
}
这将使这个测试更直观。
【问题讨论】:
-
for my $animal (@animals, "not $input") }... ;-) -
但是说真的,请使用来自List::Util 的
first。 -
哈哈,我喜欢第一个建议,但我一定会尝试
first的建议。像往常一样付费阅读文档。 -
if(grep(/$input/, @animals)){ true clause } else { equivalent of finally }
标签: for-loop foreach idioms perl