in reply to map and grep

grep expression,-or-block list

returns a new list containing those elements of list for which expression or block produces a true value, whereas

map expression,-or-block list

performs the expression or block for each element of list and returns the list of values the expression produced (i.e. one (*!) for each element supplied in the "input" list).

Both of these update the default variable $_ with the current list element before executing the expression or block. Examples:

my @sources = grep /\.c$/, glob '*'; # get only the files ending in .c + from a listing of the working directory my @objects = map s/\.c$/\.o/, @sources; # get the list of object file +s that a c compiler would make by default from the files now in @sour +ces my @virgins = map { my $c = $_; $c =~ s/\.o$/\.c/; system "cc $c"; $c } grep !(-f), @objects; # find and compile the uncompiled sources
(*! Update: unless of course the expression generates more than one or zero values per iteration as johngg points out below)

-M

Free your mind

Replies are listed 'Best First'.
Re^2: map and grep
by johngg (Canon) on Feb 20, 2007 at 15:43 UTC
    (i.e. one for each element supplied in the "input" list)

    That's usually what happens but you can produce more than one "output" for each "input", like this for example

    $ perl -le ' -> @list = map { ($_ - 1, $_, $_ + 1) } 3, 6, 9; -> print qq{@list};' 2 3 4 5 6 7 8 9 10 $

    Cheers,

    JohnGG