Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

How can I access the index variable in map?

by Anonymous Monk
on Nov 02, 2000 at 07:02 UTC ( [id://39590]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

# This works:
@a = (1,1,1); @b = (2,2,2); foreach $i (0 .. $#a) { $a[$i] += $b[$i]; }
but I'd like to use map. Is there a way to access the map index [$i] variable so I can do something like this:
@a = map $a[$i] + $_, @b;
Or is it simply not worth it?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I access the index variable in map?
by Kanji (Parson) on Nov 02, 2000 at 08:23 UTC

    Try ...

    @a = map { $a[$_] + $b[$_] } 0 .. $#b;

    ... or ...

    my $i = 0; @a = map { $a[$i++] + $_ } @b;
Re: How can I access the index variable in map?
by chromatic (Archbishop) on Nov 02, 2000 at 07:48 UTC
    To my knowledge, there's no index iterator in the map construct, presumably because it operates on lists (not just arrays).

    Stick with a for loop of some kind.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://39590]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (8)
As of 2024-07-17 14:12 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.