Skip to Content
Programming Perl, 4th Edition
book

Programming Perl, 4th Edition

by Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
February 2012
Intermediate to advanced
1184 pages
37h 17m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 4th Edition

grep

grep EXPR, LIST
grep BLOCK LIST

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 ? $_ : () } @in

For 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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Perl, 3rd Edition

Programming Perl, 3rd Edition

Larry Wall, Tom Christiansen, Jon Orwant
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9781449321451Supplemental ContentErrata Page