Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

da (1525)

  (email not shown publicly)
AOL IM: daatcoderdotcom (Add Buddy, Send Message)
Public Calendar: Subscribe, Download

Linux and perl guy working for the Computer Science department [] at the University of Waterloo []. For resume check here [].

Journal of da (1525)

Tuesday October 29, 2002
08:47 PM

mapcar- not new, but new to me

[ #8671 ]
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 <>
Subject: Re: Iterating down two lists at the same time

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:

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;

    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,
The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.