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

I'm trying to create a 3 dimensional array

I've done two dimensionals.. (just a snipit for printing it)

@nine = (0,1,2,3,4,5,6,7,8); foreach $row (@nine) { foreach $column (@nine) { print "$matrix[$row][$column]"; } print "\n"; }

But the three dimensionals seem beyond me. This piece is supposed to pull items off of some input $_ one buy one and push them one by one to a different array (thats inside of an array called column, thats inside of an array called row)

I had the two dimensional version pulling one by one off of $_ and assigning them to the elements in $matrix$row$column and that worked fine.

foreach $row(@nine) { foreach $column(@nine) { s/\d//; push(@matrix[$row][$column], $&); } }

Basically I want a 9 by 9 matrix that hold an array instead of just a scaler.

I can implement the array I want well enough the long way.. But as you see in my horrible code, I don't have the knowledge required to reference it.

Oh please, mighty perl monks, lend me your knowledge so that I might continue on my perl journey

Replies are listed 'Best First'.
Re: Multi-dimensional arrays...
by ikegami (Patriarch) on May 31, 2009 at 18:17 UTC

    Basically I want a 9 by 9 matrix that hold an array instead of just a scaler.

    for my $row (0..8) { for my $col (0..8) { my @record = ...; $data[$row][$col] = \@record; } }

    If the above "..." is built using a loop, you can avoid the intermediary variable @record:

    for my $row (0..8) { for my $col (0..8) { for my $x (...) { push @{ $data[$row][$col] }, $x; } } }

      Wouldn't this solution make all elements of the double array point to the same reference, which means the same array?

      What if they need to each have there own separate array?

        No, the my @record = ...; inside the inner loop creates a new lexically scoped array each iteration. Consider the following code.

        $ perl -Mstrict -wle ' > my @arr; > foreach my $iter ( 1 .. 3 ) > { > my @rec = map { $_ * $iter } ( 1, 2, 3 ); > push @arr, \ @rec; > } > print qq{$_: @$_} for @arr;' ARRAY(0x22aa8): 1 2 3 ARRAY(0x22b14): 2 4 6 ARRAY(0x22b80): 3 6 9 $

        Note how the references are different for each element of @arr and the contents reflect the value of $iter each time through the loop.

        I hope this is helpful.

        Cheers,

        JohnGG

Re: Multi-dimensional arrays...
by Anonymous Monk on May 31, 2009 at 18:15 UTC
Re: Multi-dimensional arrays...
by locked_user sundialsvc4 (Abbot) on May 31, 2009 at 22:06 UTC
    When you are dealing with "many dimensional arrays," sometimes a better way to visualize it, and to implement it, is by a general container-class having a list (an "n-tuple") as its key ... This can be obtained readily, and it can make your code much easier to build and to maintain.
Re: Multi-dimensional arrays...
by hda (Chaplain) on Jun 01, 2009 at 05:40 UTC