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

Hi

I would like to add some arrays to an existing array so that I end up with an array of arrays. I have tried push, but this just adds the elements of the sub-array to the master array. I would like the value of the elements in the master array to be the sub-arrays themselves.

I have also tried:

$masterarray[0]=@subarray0; $masterarray[1]=@subarray1;

etc. , but this just assigns the first element of the subarray, instead of the whole subarray, to the element of the master array.

Help!

TIA,

C

Replies are listed 'Best First'.
Re: creating arrays of arrays
by Zaxo (Archbishop) on May 06, 2004 at 16:26 UTC

    Try

    $masterarray[0] = \@subarray0; $masterarray[1] = \@subarray1;
    An array element must be a scalar, so an AoA has array references as top level elements. push works with that, too.

    After Compline,
    Zaxo

Re: creating arrays of arrays
by davido (Cardinal) on May 06, 2004 at 16:29 UTC
    You have to add your subarrays by reference. Here's one way:

     push @masterarray, \@subarray;

    If, by chance, you'll be reusing @subarray repeatedly, you may want to push a reference to an anonymous copy of it instead so that the original is preserved. You can do that like this:

     push @masterarray, [@subarray];

    You should have a look at perlreftut, perllol, and perlref. The first of those three documents is a tutorial on references. The second is a sort of cookbook for manipulating "lists of lists" or "arrays of arrays". And the third is an in depth discussion of references. All very helpful. If you plan to use Perl more than once in your life, it will pay to spend an hour or so reading those three docs.


    Dave

Re: creating arrays of arrays
by Fletch (Bishop) on May 06, 2004 at 16:27 UTC

    Actually it assigns the number of elements in each, but that's neither here nor there. You need to read perldoc perllol carefully, and perldoc perlreftut (specifically the parts about [] and \).

Re: creating arrays of arrays
by Art_XIV (Hermit) on May 06, 2004 at 20:22 UTC

    push will also work without explicitly defining your sub-arrays and getting references to them, as in the following:

    use strict; use warnings; use Data::Dumper; my @letter_array = (); my @letters = ('A' .. 'Z'); foreach my $letter (@letters) { my $selection = int rand 4; push @{$letter_array[$selection]}, $letter; } print Dumper(\@letter_array);

    Will produce (in at least one case):

    $VAR1 = [ [ 'F', 'K', 'O', 'T', 'U', 'V', 'X' ], [ 'B', 'I', 'Q', 'W' ], [ 'A', 'D', 'E', 'H', 'J', 'L', 'M', 'P', 'S', 'Z' ], [ 'C', 'G', 'N', 'R', 'Y' ] ];

    This works because of autovivification. Check perlref in your docs if this fifty-pfenning term piques your interest.

    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"