Perl 的 grep 不适用于取消引用的数组
Perl's grep does not work with dereferenced array
我想找到一个相当于 python var 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" 的第一次测试成功,而 "tomato" 的第二次测试失败:
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.
我想找到一个相当于 python var 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" 的第一次测试成功,而 "tomato" 的第二次测试失败:
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.