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

hello

my @arrays = ([2,4,6],[8,9,5],[1,2,3]); print $arrays[1][2]; my @secondArr = $arrays[1]; print "@secondArr";
the output of the first print is 5
now i want to assign all the second array to a variable
but i can't do that without going to the elements of the second array one by one, certainly there is a syntax for that. i want @secondArr to contain (8,9,5) so the second print will print 8,9,5
regards

Replies are listed 'Best First'.
Re: array of arrays
by moritz (Cardinal) on Dec 06, 2010 at 09:58 UTC

      Don't forget the gory details: perlref.

Re: array of arrays
by suhailck (Friar) on Dec 06, 2010 at 09:53 UTC
    perl -le '@arrays = ([2,4,6],[8,9,5],[1,2,3]); @secondArr=@{$arrays[1]}; print "@secondArr"' 8 9 5
Re: array of arrays
by 7stud (Deacon) on Dec 07, 2010 at 03:03 UTC

    This line:

    my @arrays = ([2,4,6],[8,9,5],[1,2,3]);

    creates an array of references, like this:

    @arrays = ($ref1, $ref2, $ref3);

    Your array access here:

    print $arrays[1][2];

    is shorthand for:

    $arrays[1]->[2]

    which is shorthand for:

    @{$arrays[1]} [2]

    Because the elements of @arrays are references, in order for you to get the second reference, you would write this:

    $arrays[1]

    And to convert a reference to the actual array (i.e. dereference the reference), you would write this:

    @{$arrays[1]}

    Braces are used to turn a reference into the thing it references.