Perl 的 grep 不适用于取消引用的数组



我想找到一个相当于pythonvar in list成语的perl,并偶然发现了这个。

perl grep 可以执行一个grep { $_ eq $var } @list表达式来匹配列表逻辑中的元素。

如果我使用像grep { $_ eq $var } @$list这样的去围栏数组,$list定义为 ['foo', 'bar'],我不会得到相同的结果。

有没有办法让 grep 使用取消引用的数组工作?

这个成语应该可以正常工作;我认为一个不起作用的代码示例会有所帮助。 不过,举一个快速玩具的例子:

#!/usr/bin/perl
use strict;
use warnings;
use Test::More;
sub find_var {
my ($var,$array) = @_;
print "Testing for $var in [" . join(',',@$array) . "]...n";
if ( grep $var eq $_, @$array ) {
return "found it";
} else {
return "no match!n";
}
}
my @array = qw(apple pear cherry football);
my $var = 'football';
my $var2 = 'tomato';
is(find_var($var, @array), 'found it');
is(find_var($var2, @array), 'found it');
done_testing();

这将产生以下输出,指示数组引用中"football"的第一个测试成功,而"番茄"的第二个测试不成功:

Testing for football in [apple,pear,cherry,football]...
ok 1
Testing for tomato in [apple,pear,cherry,football]...
not ok 2
#   Failed test at array.pl line 22.
#          got: 'no match!
# '
#     expected: 'found it'
1..2
# Looks like you failed 1 test of 2.

最新更新