The grep() function

The grep() function is used to search a list for elements which match a certain regexp pattern. It takes two arguments - a pattern and a list - and returns a list of the elements which match the pattern.

The grep() function is on page 178 of your Camel book.

# trivially check for valid email addresses
my @valid_email_addresses = grep /\@/, @email_addresses;

The grep() function temporarily assigns each element of the list to $_ then performs matches on it.

There are many more complicated uses for the grep function. For instance, instead of a pattern you can supply an entire block which is to be used to process the elements of the list.

my @long_words = grep { (length($_) > 8); } @words;

grep() doesn't require a comma between its arguments if you are using a block as the first argument, but does require one if you're just using an expression. Have a look at the documentation for this function to see how this is described.

Exercises

  1. Use grep() to return a list of elements which contain numbers (Answer: exercises/answers/grepnumber.pl)

  2. Use grep() to return a list of elements which are

    1. keys to a hash (Answer: exercises/answers/grepkeys.pl)

    2. readable files (Answer: exercises/answers/grepfiles.pl)