Picking Items from a List with grep
Sometimes you’ll only want certain items from a list. Maybe it’s the odd numbers selected from a list of numbers, or the lines mentioning Fred from a file of text. As you’ll see in this section, picking some items from a list can be done with the grep operator.
Let’s try that first one and get the odd numbers from a large list of numbers. We don’t need anything new to do that:
my @odd_numbers;
foreach (1..1000) {
push @odd_numbers, $_ if $_ % 2;
}That code uses the modulus operator (%), which you saw in Chapter 2. If a number is even, that number “mod two” gives zero, which is false. But an odd number will give one; since that’s true, only the odd numbers will be pushed onto the array.
The code is all right as it stands except that it’s a little longer to write and slower to run than it might be since Perl provides the grep operator:
my @odd_numbers = grep { $_ % 2 } 1..1000;That line gets a list of 500 odd numbers in one quick line of code. How does it work? The first argument to grep is a block that uses $_ as a placeholder for each item in the list, and returns a Boolean (true/false) value. The remaining arguments are the list of items to search through. The grep operator will evaluate the expression once for each item in the list as our original foreach loop did. For the ones where the last expression of the block returns a true value, that element is included in the list that results from grep.
While the grep is running, $_ is aliased to one ...
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.
Read now
Unlock full access