http://qs321.pair.com?node_id=1101592


in reply to Perl nested loop to print out two arrays n number of times in different patterns

Read How do I post a question effectively? if you want good answers. We really encourage people who show they are trying to learn. Posting what seems to be a homework question without even showing an attempt to solve it and also providing an inconsistent example of the required output sets a lot of red-flags that will make many monks refrain from answering. If you want good answers you post good questions.

With that said, the following code gets closer to what you want, you can expand on it by holding the index values for each array at any given iteration and reporting that. This is left as an exercise to the OP.

my @numbers=(1,2,3); my @letters=("a","b","c"); for(0..$#numbers){ my $arr_curr_val= $numbers[$_]; for(0..$#letters){ print "$arr_curr_val\t$letters[$_]\n"; } }
Update: gave the arrays meaningful names rather than @array1 and @array2. Thanks to Anonymous Monk who pointed that out.

A 4 year old monk

Replies are listed 'Best First'.
Re^2: Perl nested loop to print out two arrays n number of times in different patterns
by johngg (Canon) on Sep 23, 2014 at 09:48 UTC

    If instead of using array indexes you use the actual array values is saves the bother of having to save the current outer loop value. Anonymonk makes a useful point about meaningful variable names.

    $ perl -Mstrict -Mwarnings -E ' my @nums = qw{ 1 2 3 }; my @ltrs = qw{ a b c }; my $iters = 2; for my $iter ( 1 .. $iters ) { for my $num ( @nums ) { for my $ltr ( @ltrs ) { say qq{$num$ltr}; } } }' 1a 1b 1c 2a 2b 2c 3a 3b 3c 1a 1b 1c 2a 2b 2c 3a 3b 3c $

    Another way to do this would be to localise the list separator and use glob and the list multiplier in a do block.

    $ perl -Mstrict -Mwarnings -E ' my @nums = qw{ 1 2 3 }; my @ltrs = qw{ a b c }; my $iter = 2; say for do { local $" = q{,}; ( glob qq{{@nums}{@ltrs}} ) x $iter; };' 1a 1b 1c 2a 2b 2c 3a 3b 3c 1a 1b 1c 2a 2b 2c 3a 3b 3c $

    I hope this is of interest.

    Cheers,

    JohnGG

Re^2: Perl nested loop to print out two arrays n number of times in different patterns
by Anonymous Monk on Sep 23, 2014 at 06:41 UTC

    ... good advice ... @array1 ... @array2 ...

    Hi :) @numbers and @letters :)