In a previous tutorial I demonstrated how you can search a Perl list/array of strings for another string, or a regular expression using Perl's grep
function. In this example I'll demonstrate how you can search a list of numbers very easily, also using Perl's grep
function.
Here's a simple example, where I first create an array of numbers, then search that array for any number whose modulus when divided by 10 is zero. Here's the Perl source code:
# create a list/array of numbers @numbers = (1..100); # search @numbers @results = grep { $_ % 10 == 0 } @numbers; # print the results print "@results\n";
As you can see from the following results, this code prints every number that is evenly divisible by 10:
10 20 30 40 50 60 70 80 90 100
How grep works with lists of numbers
Here's how this works:
- The first argument to
grep
is a block. - The block uses the
$_
variable as a placeholder for each item in the list. - The block just needs to evaluate to true or false.
- The other argument to
grep
is the list that I want to search through. - The
@results
array is built from all of the values whose test evaluates totrue
.
As you can see from this simple algorithm, you can put any test you want inside that block. Your test (your business logic) then controls what goes into the @results
array.
For example, if I shorten up my list to twelve numbers, and then have my block evaluate to 1
, like this:
@numbers = (1..12); @results = grep { 1 } @numbers; print "@results\n";
I'll get the following output:
1 2 3 4 5 6 7 8 9 10 11 12
Conversely, if I change that 1
("true") to a 0
("false"), like this:
@numbers = (1..12); @results = grep { 0 } @numbers; print "@results\n";
I'll just get a blank string as output.
I think this approach is very cool on a number of levels, especially because it greatly shortens up your code, while it's still very readable.