【问题标题】:Perl's grep does not work with dereferenced array [closed]Perl 的 grep 不适用于取消引用的数组 [关闭]
【发布时间】:2017-12-19 11:07:45
【问题描述】:

我想找到一个相当于 python var in list idiom 的 perl 并偶然发现了这个。

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

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

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

【问题讨论】:

  • 你能说得更具体点吗?请发布minimal reproducible examplemy $var = 'foo'; say for grep { $_ eq $var } @{ [qw/foo bar/] } 对我来说就像 5.20.1 的魅力。
  • List::Util::any 在这种情况下可能比grep 更好,因为它在第一次匹配后停止。
  • Data::Munge::elem 也可以这样做。

标签: arrays perl grep dereference


【解决方案1】:

这个成语应该很好用;我认为一个不起作用的代码示例会有所帮助。不过,这只是一个快速的玩具示例:

#!/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.

【讨论】:

  • 刚刚意识到我的错误是一个简单的错字,是的,这个成语应该适用于取消引用的数组
猜你喜欢
  • 2017-07-18
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多