I overheard this on "Fun with Perl" today. The 'mapcar' ideom looks incredibly
useful for traversing more than one list at a time.
--------------
Date: Tue, 29 Oct 2002 14:24:13 -0500
From: Evan A. Zacks
On Tue, Oct 29, 2002 at 01:05:12 PM, Bernie Cosell wrote:
> I was wondering if there's any fun to be found in elegant/clever ways to
> traverse two lists at the same time... I envisioned something like:
> map2 {stuff} \@list1, \@list2
> where inside the map maybe you had $a and $b aliased appropriately
> or something
> like that. Or perhaps:
> mapn {stuff} list-of-listrefs
> where you aliased $1, $2, $3, ... to the parallel entries from the different
> lists...
Hello Bernie,
You may be interested in mapcar, a module written by Tye on Perlmonks:
http://www.perlmonks.org/index.pl?node_id=44763
http://www.perlmonks.org/index.pl?node_id=44763&displaytype=displaycode
You call the mapcar function as you specified above:
use mapcar;
my @a= qw( foo bar baz );
my @b= qw( qux quux quo );
print mapcar { "@_\n" } \@a, \@b;
__END__
foo qux
bar quux
baz quo
Inside the block that you pass to mapcar, the two elements from
the lists you are traversing are stored in @_.
>From Perlmonks:
mapcar is from lisp. It is like map but works on more than
one list. While map loops setting $_ to successive elements of a
list, mapcar loops setting @_ to successive elements of several
lists (but since you can only pass one list to a subroutine,
mapcar expects a list of references to one or more arrays). Both
map and mapcar collect the values returned by the code block or
subroutine and then return the collected values.
Hope this helps,
-E