Perl - how to search a list of numbers with the grep function

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:

  1. The first argument to grep is a block.
  2. The block uses the $_ variable as a placeholder for each item in the list.
  3. The block just needs to evaluate to true or false.
  4. The other argument to grep is the list that I want to search through.
  5. The @results array is built from all of the values whose test evaluates to true.

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.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.