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

It has been a while since I needed to delve into perl scripting and I've run across a fairly simple problem, I expect, but cannot, in short work, find a simple solution.

I have multiple arrays (that for other reasons need to remain seperate) that I would like to run the same foreach loop on. I realize that one solution would be to have the code be in a sub-routine and run each arrary through it.

However, I was wondering if it were possible to have something similar to  foreach (@array1 @array2 @array3)

Thanks in advance,
magnus

Replies are listed 'Best First'.
Re: Foreach in mulitple arrays
by ikegami (Patriarch) on Jun 13, 2005 at 15:27 UTC

    yes, you're only missing commas:

    @array1 = qw( a b ); @array2 = qw( c d ); @array3 = qw( e f ); foreach (@array1, @array2, @array3) { print; } # output # ------ # abcdef

    If you wanted to go through them in parallel:

    @array1 = qw( a b ); @array2 = qw( c d ); @array3 = qw( e f ); # Assumes all array are the same length. foreach (0..$#array1) { print($array1[$_], $array2[$_], $array3[$_], "\n"); } # output # ------ # ace # bdf
      Thank you both. It worked fine.
Re: Foreach in mulitple arrays
by BrowserUk (Patriarch) on Jun 13, 2005 at 15:26 UTC

    Add 2 commas and that will work.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Re: Foreach in mulitple arrays
by ambrus (Abbot) on Jun 13, 2005 at 18:17 UTC

    Adding the commas indeed work. However, there's another, more general possibility too: factor the loop body out to a function and use three different foreach loops. Like, instead of

    for (@array1, @array2, @array3) { print "met $_"; }
    you can write
    my $body = sub { print "met $_"; } for (@array1) { &$body() } for (@array2) { &$body() } for (@array3) { &$body() }
    This works even if you have a more complicated iterator than foreach.