Dylan has asked for the wisdom of the Perl Monks concerning the following question:

So: I have two arrays that I need to go over at the same
time, value by value, and print them.
Foreach only seems to want to do one array..
What ever am I to do?

Replies are listed 'Best First'.
Re: Foreach two arrays?
by blakem (Monsignor) on Sep 06, 2001 at 10:09 UTC
    How about using the same index variable to loop through each array:
    #!/usr/bin/perl -wT use strict; my @a = qw(1 2 3 4 5 6); my @b = qw(a b c d e f g h i); my $max = $#a > $#b ? $#a : $#b; # find the max index of the biggest +array for my $i (0..$max) { # loop through using the same index +variable print "$a[$i]\n" if defined $a[$i]; print "$b[$i]\n" if defined $b[$i]; } =OUTPUT 1 a 2 b 3 c 4 d 5 e 6 f g h i

    -Blake

      Or you could controversially use the 'for' loop as used in pre-perlhistoric times -
      @a = qw(look the for); @b = qw(at lovely loop); for($i = 0; $i < @a; $i++) { print "$a[$i] $b[$i] "; }
      resulting in -
      look at the lovely for loop

      Just my $0.02 (not that I'm one to arbitrarily dispense money ;o)

      broquaint

      Ohh Ahh :)

      I like that.

Re: Foreach two arrays?
by mirod (Canon) on Sep 06, 2001 at 10:11 UTC

    The simplest is probably:

    foreach my $v1 (@array1) { my $v2= shift @array2; print $v1, $v2; }

    Of course this relies on @array1 and @array2 having the same number of elements!

    If the arrays can have different sizes then you can do:

    # print all elements while( @array1 || @array2) { my $v1= shift @array1 || "empty"; # or whatever default value my $v2= shift @array2 || "empty"; print $v1, $v2; }
    # print elements up to the shortest array length while( @array1 && @array2) { my $v1= shift @array1; my $v2= shift @array2; print $v1, $v2; }

    I can't wait to see the golf versions!

Re: Foreach two arrays?
by George_Sherston (Vicar) on Sep 06, 2001 at 10:54 UTC
    while (@a || @b) {print shift @a,shift @b}
    Insta-update - alas, alas, too slow. How about this, if they're always the same length:
    for(@a){print$_,$b[$0];$0++}


    § George Sherston
      how about
      print$_,$b[$0++]for@a
      ;)
         larryk                                          
      perl -le "s,,reverse killer,e,y,rifle,lycra,,print"
(tye)Re: Foreach two arrays?
by tye (Sage) on Sep 06, 2001 at 23:11 UTC

    See also mapcar.

            - tye (but my friends call me "Tye")
Re: Foreach two arrays?
by Rhandom (Curate) on Sep 06, 2001 at 20:43 UTC
    Yet another...

    print $_,shift(@b) for @a; # OR print shift(@a),shift(@b) while @a; # might have been done already # OR $i = 0; @c = map { $_, $b[$i++] } @a; # gives a new array with the values


    my @a=qw(random brilliant braindead); print $a[rand(@a)];