grep
grepEXPR,LISTgrepBLOCKLIST
This function evaluates EXPR or
BLOCK in Boolean context for each element of
LIST, temporarily setting $_ to each element in turn, much like the
foreach construct. In list context,
it returns a list of those elements for which the expression is true.
(The operator is named after a beloved Unix program that extracts lines
out of a file that match a particular pattern. In Perl, the expression
is often a pattern, but it doesn’t have to be.) In scalar context,
grep returns the number of times the
expression was true.
If @all_lines contains lines of
code, this example weeds out comment lines:
@code_lines = grep !/^\s*#/, @all_lines;
Because $_ is an implicit alias
to each list value, altering $_
modifies the elements of the original list. While this is useful and
supported, it can occasionally cause bizarre results if you aren’t
expecting it. For example:
@list = qw(barney fred dino wilma);
@greplist = grep { s/^[bfd]// } @list;@greplist is now “arney”, “red”, “ino”, but @list is now “arney”, “red”, “ino”, “wilma”! Ergo, Caveat Programmor.
See also map. The following two
statements are functionally equivalent:
@out = grep { EXPR } @in;
@out = map { EXPR ? $_ : () } @inFor a version of grep that
short circuits, see the first
function from the standard List::Util module. Instead of returning a list of all elements for
which the EXPR was true, it returns only the
first such, or undef if none were. As
always, $_ is set to each
element:
use List::Util qw(first); ...