Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the item in an array that meets a specific criteria if there is one (Perl)?

Tags:

arrays

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

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

like image 651
CW Holeman II Avatar asked Dec 01 '22 10:12

CW Holeman II


2 Answers

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";
}
like image 171
Eric Strom Avatar answered Dec 06 '22 10:12

Eric Strom


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...
 }
like image 43
Ether Avatar answered Dec 06 '22 10:12

Ether