Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: iterating 2 arrays in parallel

by linuxer (Curate)
on Apr 15, 2009 at 09:48 UTC ( #757607=note: print w/replies, xml ) Need Help??

in reply to iterating 2 arrays in parallel

use List::MoreUtils qw( pairwise ); my @combined = pairwise { $a .':'. $b } @array1, @array2;

See List::MoreUtils for details.

Replies are listed 'Best First'.
Re^2: iterating 2 arrays in parallel
by citromatik (Curate) on Apr 15, 2009 at 10:16 UTC

    pairwise from List::MoreUtils requires that both arrays have the same length, you can get the same behaviour easily without using any extra module at all:

    my @combined = map {"$a1[$_]:$a2[$_]"} ($#a1 < $#a2 ? (0..$#a2) : (0.. +$#a1));

    This version can be easily fixed to treat arrays of different length:

    my @combined = map {($a1[$_]//"").":".($a2[$_]//"")} ($#a1 < $#a2 ? (0 +..$#a2) : (0..$#a1));


      The given example uses arrays of the same length, so pairwise looks fine to me.

      And if they are not of the same length, I think the same way as JavaFan, that iswas left as an exercise to the reader. I don'tdidn't want to guess, what has to happen if the lengths differ. It's the OP who should know, what to do.

      Nevertheless, thanks for your examples ;o)


      What about this pairwise solution to work with arrays of different lengths:

      use List::MoreUtils qw( pairwise ); my @a=(1 .. 5 ); my @b=( 'a' .. 'c' ); ### Good point from JavaFan; bad idea to ignore 0 ### my @combined = pairwise { ( $a || '' ) .':'. ( $b || '' ) } @a, @b +; ### fixed: my @combined = pairwise { ( defined $a ? $a : '' ) .':'. ( defined $b +? $b : '' ) } @a, @b; { local $,="\n", print @combined; }
        I think it's a bad idea to replace a 0 with an empty string as your solution does. Either use defined, '//', or just turn off warnings.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://757607]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2018-06-22 00:00 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (120 votes). Check out past polls.