如果存在符合特定条件的数组项,是否有一种Perl惯用语来查找该项?
my $match = 0;
foreach(@list){
if (match_test($_)){
$result = $_;
$match = 1;
last;
}
}
$match || die("No match.");
say $result, " is a match.";
这个例子看起来有点别扭。我希望Perl能够有更干净的处理方式。
是的,grep 就是你要找的:
my @results = grep {match_test($_)} @list;
grep
返回@list
中match_test
为真的子集。在大多数其他函数语言中,grep
被称为filter
。
如果您只想要第一个匹配项,请使用List::Util
中的first
函数。
use List::Util qw/first/;
if (my $result = first {match_test($_)} @list) {
# use $result for something
} else {
die "no match\n";
}
my @matches = grep { match_test($_) } @list;
如果只有一个匹配项,List::Util 的 'first' 更快(假设找到了匹配项):
use List::Util 'first';
if (my $match = first { match_test($_)} @list)
{
# do something with the match...
}
$scalar
在@array
中时,表达式@array ~~ $scalar
为真。 - daxim$scalar ~~ @array
。请注意,为了帮助理解,将 ~~ 看作 "in" 的同义词。 - draegtun