next up previous contents
Next: substr Up: A Few Perl Functions Previous: Introduction   Contents


map and grep

As an alternative to the foreach loop described in Section 5.6, perl provides the map function. The map function differs from most other perl functions in that its first argument is an expression or function, rather than a scalar, list, or hash. This argument is evaluated for each element of a list, passed as a second argument to map, and the results are returned by map as another list. Inside the expression, the usual default variable $_ takes the role of each element from the list in turn. Suppose we have a array called @files containing filenames, and we wish to create a similar array called @sizes containing the sizes of those files. Although this could be done with a loop, map makes the job much easier:
     @sizes = map(-s,@files);
The expression ``-s'', uses $_ as its default argument, so it will return the size of each file in turn. Using map saves us the trouble of explicitly adding each size to the resulting array. If we wanted to create a hash, with the filenames as keys, and the sizes as values, map also makes it easy.
     map($sizes{$_} = -s ,@files);
In this case, we ignored the return value, since the expression passed to map explicitly created elements in the %sizes hash.

If you pass a function as the first argument to map, make sure that it operates on the default variable $_, since map does not pass any arguments to a function. If you've written a function for some other purpose, you can simply pass an expression, calling that function with $_ as an argument.

The function grep also takes two arguments, the first being an expression and the second being a list. Like map, the first argument is evaluated with each element of the second argument taking the role of $_ in turn, but grep simply returns the list element if the expression was true, and does nothing otherwise. Thus, grep can be used as a filter to extract those elements of a list for which an expression is true. Probably the most common use of grep is to pass a regular expression as the first argument, but you can use any expression that evaluates to true for the elements you want and false for the elements you don't want.

Suppose we have an array of filenames called @files, and we want a second list called @jpgs containing only those filenames which end in the extension ``.jpg''. Instead of using a loop, we could employ grep as follows:

     @jpgs = grep(/\.jpg$/,@files);

As another example, suppose we have a list of files and we want to eliminate all the directories from the list.

     @use = grep(! -d ,@files);


next up previous contents
Next: substr Up: A Few Perl Functions Previous: Introduction   Contents
Phil Spector 2002-10-18