4.13. Finding All Elements in an Array Matching Certain CriteriaProblemFrom a list, you want only the elements that match certain criteria. This notion of extracting a subset of a larger list is common. It's how you find all engineers in a list of employees, all users in the "staff " group, and all the filenames you're interested in. SolutionUse @MATCHING = grep { TEST ($_) } @LIST;DiscussionThis could also be accomplished with a @matching = ();
foreach (@list) {
push(@matching, $_) if TEST ($_);
}The Perl @bigs = grep { $_ > 1_000_000 } @nums;
@pigs = grep { $users{$_} > 1e7 } keys %users;Here's something that sets @matching = grep { /^gnat / } `who`;Here's another example: @engineers = grep { $_->position() eq 'Engineer' } @employees;It extracts only those objects from the array You could have even more complex tests in a @secondary_assistance = grep { $_->income >= 26_000 &&
$_->income < 30_000 }
@applicants;But at that point you may decide it would be more legible to write a proper loop instead. See AlsoThe "For Loops," "Foreach Loops," and "Loop Control" sections of perlsyn (1) and Chapter 2 of Programming Perl; the |