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. Solution
Use
@MATCHING = grep { TEST ($_) } @LIST;
Discussion
This 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 Also
The "For Loops," "Foreach Loops," and "Loop Control" sections of
perlsyn
(1) and
Chapter 2
of
Programming Perl
; the ![]() Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|