查找符合特定条件,如果有一个(的Perl)数组中的项目? [英] Find the item in an array that meets a specific criteria if there is one (Perl)?

查看:386
本文介绍了查找符合特定条件,如果有一个(的Perl)数组中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个Perl的成语在满足特定条件,如果有一个数组寻找项目?

Is there a Perl idiom for finding the item in an array that meets a specific criteria if there is one?

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

这个例子似乎有点尴尬。我希望的Perl有东西更清洁处理这个问题。

The example seems a bit awkward. I expect Perl to have something to handle this more cleanly.

推荐答案

是的,的grep 是你在找什么:

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

的grep 返回 @list ,其中 MATCH_TEST 返回真。 的grep 被称为过滤器在大多数其他功能的语言。

grep returns the subset of @list where match_test returned true. grep is called filter in most other functional languages.

如果您只想在第一场比赛中,使用第一来自的列表::的Util

if you only want the first match, use first from List::Util.

use List::Util qw/first/;

if (my $result = first {match_test($_)} @list) {
    # use $result for something
} else {
    die "no match\n";
}

这篇关于查找符合特定条件,如果有一个(的Perl)数组中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆