开发者

Find the item in an array that meets a specific criteria if there is one (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 m开发者_如何学编程atch.");
say $result, " is a match.";

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


Yes, grep is what you are looking for:

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

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

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";
}


If there could be multiple matches:

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

If there could only be one match, List::Util's 'first' is faster (assuming a match is found):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜