For loop 优雅的接球方式;对于循环到达的最后一个元素";?
有时在Perl中,我为/For loop 优雅的接球方式;对于循环到达的最后一个元素";?,for-loop,foreach,idioms,perl,For Loop,Foreach,Idioms,Perl,有时在Perl中,我为/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; } } # <--
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;
}
}
# <-----
这将使此测试更加直观。您可以使用标记块将循环包装为如下所示:
outer: {
foreach my $animal (@animals) {
if ($input eq $animal) {
print "Ah, yes, an $input is an animal!\n";
last outer;
}
}
print "no animal found\n";
}
只要让循环设置一个变量,您就可以检查它是否已设置,并在以后对其进行操作:
my $found;
foreach my $animal (@animals) {
if ($input eq $animal) {
$found = $animal;
last outer;
}
}
print defined $found ? "Ah, yes, an $input is an animal!\n" : "no animal found\n";
但是对于这个特殊的问题,正如@choroba所说,只需使用List::Util中的first
(或any
)函数。或者,如果要检查大量输入,则检查散列比较容易
my %animals = map { ($_ => 1) } qw/cat dog horse/;
print exists $animals{$input} ? "Ah, yes, an $input is an animal!\n" : "no animal found\n";
这并不是最好的解决方案,但有时迭代索引会有所帮助
for my $i (0..$#animals) {
my $animal = $animals[$i];
...
}
然后,您可以检查索引是0
(第一次通过)还是$#a
(最后一次通过)。我会保持它的老套,并使用一个著名的C语言习惯(用于在第一个语句中拆分循环和一个while循环)
#/usr/bin/env perl
严格使用;
使用警告;
我的$input='lion';
我的@animals=qw/猫狗马/;
我的$index=0;
而($index
因此,“对不起,我不确定狮子是不是动物”会很自然地出现。
希望,这有帮助。注意,M.首先是最小的开销;eval避免了将其全部嵌套在if块中;因为你可能并不在乎哪一行不是动物
eval
{
my $found = first { check for an animal } @animalz
or die "Sorry, no animal found.\n";
# process an animal
1
}
// do
{
# deal with non-animals
};
对于我的$animal(@animals,“非$input”)}
…;-)但是说真的,请使用first
from。哈哈,我喜欢第一个建议,但我一定会尝试first
建议。照常付费阅读文档。if(grep(/$input/,@animals)){true子句}else{finally的等价物}
#!/usr/bin/env perl
use strict;
use warnings;
my $input = 'lion';
my @animals = qw/cat dog horse/;
my $index = 0;
while ($index < scalar @animals) {
if ($animals[ $index++ ] eq $input) {
print "Ah, yes, an $input is an animal!\n";
last;
}
}
if ($index == scalar @animals) {
print "Sorry, I'm not sure if $input is an animal or not\n";
}
eval
{
my $found = first { check for an animal } @animalz
or die "Sorry, no animal found.\n";
# process an animal
1
}
// do
{
# deal with non-animals
};