【问题标题】:Find the item in an array that meets a specific criteria if there is one (Perl)?如果有一个(Perl),则在满足特定条件的数组中查找项?
【发布时间】:2010-06-21 17:21:52
【问题描述】:

是否有 Perl 习惯用法用于在数组中查找满足特定条件的项(如果有的话)?

my $match = 0;
foreach(@list){
   if (match_test($_)){
      $result = $_;
      $match = 1;
      last;
      }
   }
$match || die("No match.");
say $result, " is a match.";

这个例子看起来有点尴尬。我希望 Perl 能够更干净地处理这个问题。

【问题讨论】:

    标签: arrays perl


    【解决方案1】:

    是的,grep 就是您要查找的内容:

    my @results = grep {match_test($_)} @list;
    

    grep 返回 @list 的子集,其中 match_test 返回 true。 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";
    }
    

    【讨论】:

    • 另外,当$scalar@array 中时,表达式@array ~~ $scalar 为真。
    • @daxim => 假设你有一个足够新的 perl 可以进行智能匹配 (5.10+)
    • @C.W.Holeman II:我在回答中给出了这两种情况的示例。
    • @daxim 等人:从 5.10.1+ 开始,~~ 的顺序很重要。因此它需要是$scalar ~~ @array NB。为了帮助我将 ~~ 视为“in”的同义词。
    【解决方案2】:

    如果可能有多个匹配项:

     my @matches = grep { match_test($_) } @list;
    

    如果只有一个匹配项,List::Util 的“第一个”会更快(假设找到匹配项):

     use List::Util 'first';
     if (my $match = first { match_test($_)} @list)
     {
          # do something with the match...
     }
    

    【讨论】:

    • 在非常大的阵列上更快,但这不是常见的情况
    • 如果结果为零也不会更快,因为仍然需要检查每个元素。
    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 2023-02-24
    • 2021-12-23
    • 2022-01-13
    • 2021-05-15
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多