@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);