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

I need some help traversing my array of arrays. The output consists of position coordinates (x,y,z) and the selected values from the array. Also, the input array has to scale from 1D to nD ("3D" shown in the example). Thanks!
# input my (@arr) = ( [ '0-0', '0-1' ], [ '1-0', '1-1', '1-2', '1-3' ], [ '2-0', '2-1', '2-2', '2-3' ] ); # ... # output (0,0,0) --> 0-0 1-0 2-0 (0,0,1) --> 0-0 1-0 2-1 (0,0,2) --> 0-0 1-0 2-2 (0,0,3) --> 0-0 1-0 2-3 (0,1,0) --> 0-0 1-1 2-0 (0,1,1) --> 0-0 1-1 2-1 (0,1,2) --> 0-0 1-1 2-2 (0,1,3) --> 0-0 1-1 2-3 (0,2,0) --> 0-0 1-2 2-0 (0,2,1) --> 0-0 1-2 2-1 (0,2,2) --> 0-0 1-2 2-2 (0,2,3) --> 0-0 1-2 2-3 (0,3,0) --> 0-0 1-3 2-0 (0,3,1) --> 0-0 1-3 2-1 (0,3,2) --> 0-0 1-3 2-2 (0,3,3) --> 0-0 1-3 2-3 (1,0,0) --> 0-1 1-0 2-0 (1,0,1) --> 0-1 1-0 2-1 (1,0,2) --> 0-1 1-0 2-2 (1,0,3) --> 0-1 1-0 2-3 (1,1,0) --> 0-1 1-1 2-0 (1,1,1) --> 0-1 1-1 2-1 (1,1,2) --> 0-1 1-1 2-2 (1,1,3) --> 0-1 1-1 2-3 (1,2,0) --> 0-1 1-2 2-0 (1,2,1) --> 0-1 1-2 2-1 (1,2,2) --> 0-1 1-2 2-2 (1,2,3) --> 0-1 1-2 2-3 (1,3,0) --> 0-1 1-3 2-0 (1,3,1) --> 0-1 1-3 2-1 (1,3,2) --> 0-1 1-3 2-2 (1,3,3) --> 0-1 1-3 2-3

Replies are listed 'Best First'.
Re: Array looping advice
by Corion (Patriarch) on Aug 11, 2008 at 08:15 UTC
Re: Array looping advice
by ikegami (Patriarch) on Aug 11, 2008 at 08:19 UTC

    When you need loops nested arbitrarily deep, think of Algorithm::Loops's NestedLoops.

    If you just need the transformed values:

    use Algorithm::Loops qw( NestedLoops ); my $i = NestedLoops(\@arr); while (my @vals = $i->()) { print(join(' ', @vals), "\n"); }

    If you need the indexes and transformed values:

    use Algorithm::Loops qw( NestedLoops ); my $i = NestedLoops([ map { [ 0..$#$_ ] } @arr ]); while (my @idx = $i->()) { my @vals = map { $arr[$_][$idx[$_]] } 0..$#idx; print('(', join(',', @idx), ') --> ', join(' ', @vals), "\n"); }
      Thanks for you both! I hadn't run into Algorithm::Loops, but it seems to be very handy in cases like this. ...always, search CPAN first:)