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

Hi, I hope I won't only get 'read perllol' as reply to my question as I have already done so.
I try to build up a three dimensional array using the push command. In perllol this is described for an array of arrays:
          push @AoA, [ @tmp ]; Can I use push to append an array to an array of arrays? E.g something like:
        push @AoA[$i], [ @tmp ]; Or could I use $#AoA[$i] in some way to determine the last index of @AoA[$i] to then add the temp array with:
foreach (@tmp) { push @AoA[$i][$#AoA[$i]+1], $_; }
Thanks 'varray' much for any help!

Replies are listed 'Best First'.
Re: three dimensional arrays
by Abigail-II (Bishop) on Nov 28, 2003 at 14:49 UTC
    Some rules: 1) the first argument of push must have a @ sigil. 2) Whenever I have a sigil followed by a variable name in Perl, I may replace the variable name with a block that returns a reference of the appropriate type.

    So, what I want is:

    push @somearray, [@tmp];
    But what should somearray be? Well, it should be a block returning a reference to the right array - and what is that array? It's $AoA [$i]. So, replacing somearray with the block, we get:
    push @{$AoA [$i]}, [@tmp];

    Abigail

Re: three dimensional arrays
by Hena (Friar) on Nov 28, 2003 at 14:26 UTC
    Its always good to read docs anonymous monk above mentioned important docs. But to push to 3-dimension, it should go like this
    # push @tmp into 3rd dimension push (@{$AoA[$i]},@tmp); # push @tmp cell to 3rd dimension # testing for proper info, not tested foreach (@{$AoA}) { next if (defined($_) && ref($_)!="ARRAY"); push (@{$_},shift @tmp); }
    Remember to make sure the cell of array you are pushing into is either undefined or array reference.
Re: three dimensional arrays
by Anonymous Monk on Nov 28, 2003 at 14:13 UTC
    read perllol, and then what perllol tells you to read(SEE ALSO perldata(1), perlref(1), perldsc(1)).

    Now for the advice, yes, you can use push.

Re: three dimensional arrays
by Anonymous Monk on Nov 28, 2003 at 14:22 UTC
    #!/usr/bin/perl -wl - use strict; my @a; $a[0][0][0] = 0; $a[0][0][1] = 1; $a[1][0][0] = 2; $a[2][0][0] = 3; print $#a; print $a[0]; print $#{$a[0]}; print $a[0][0]; print $#{$a[0][0]}; print $a[0][0][0]; print $/; print $a[1]; print $#{$a[1]}; print $a[1][0]; print $#{$a[1][0]}; print $a[1][0][0]; __END__ 2 ARRAY(0x1abf1ac) 0 ARRAY(0x1abf1d0) 1 0 ARRAY(0x1ab51fc) 0 ARRAY(0x1ab522c) 0 2
      #!/usr/bin/perl -wl - use strict; my @a = ( [ [ 0, 1 ] ], [ [ 2 ] ], [ [ 3 ] ] ); print $#a; print $a[0]; print $#{$a[0]}; print $a[0][0]; print $#{$a[0][0]}; print $a[0][0][0]; print $/; print $a[1]; print $#{$a[1]}; print $a[1][0]; print $#{$a[1][0]}; print $a[1][0][0]; __END__ 2 ARRAY(0x1abf1dc) 0 ARRAY(0x1abf0f8) 1 0 ARRAY(0x1ab5214) 0 ARRAY(0x1ab51cc) 0 2