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.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With