in reply to read 2 array simultaneously

There are more than enough Ways To Do It already presented - I just want to point out that the first three Ways were all assuming that the two arrays were of the same size. What happens when the arrays are different lengths depends on which solution you use. Ovid's solution was the most work, but if it is possible that the arrays are different sizes, that solution is the most robust, handling all cases quite well. Note that in that solution, the shorter array, if there is one, will be treated as if it were filled with undef's - which your code would have to handle, e.g.,

printf "%s:%s %s:%s\n", $x, defined $item ? $item : '<undef>', $y, defined $element ? $element : '<undef>';

Replies are listed 'Best First'.
Re^2: read 2 array simultaneously
by xdg (Monsignor) on Jan 12, 2005 at 04:40 UTC

    Well, the first reply above was explicitly coded to the OP's questions and the second said it assumed equal length, so they were at least thinking about it but the undef handling is a good point. TIMTOWDI is fun and good practice. How about this? Handles different sized arrays and prints undefs nicely, too.

    use strict; my @a = qw( 1 2 3 ); my @b = qw( 7 8 9 10 ); my ($x, $y) = (1, 2); for (my $i = 0; $i < @a || $i < @b; ) { printf( "$x: %s $y: %s\n", map { defined $_ ? $_ : 'undef' } ( $a[$i], $b[$i++] ) ); }

    update: side effect -- will extend the shorter array with undefs. Could copy @a and @b before handing to the loop if this was a concern.

    -xdg

    Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.