http://www.perlmonks.org?node_id=11107018

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

Hello Monks,

I am trying to store a set of arrays into a master array for later processing. In my example below, I have 5 arrays that I want to store in a master array called @rows. But when I try printing the values in @rows, it only displays the first element of each row. Any help would be appreciated.

Ken

my @row1 = qw(71 22 15 10 51); my @row2 = qw(91 82 28 11 91); my @row3 = qw(11 72 37 58 20); my @row4 = qw(21 42 63 24 16); my @row5 = qw(81 32 53 54 42); my @rows = (); @rows[0] = @row1; @rows[1] = @row2; @rows[2] = @row3; @rows[3] = @row4; @rows[4] = @row5; $i = 0; while ($i <= 4) { print "@rows[$i]\n"; $i++; }

Replies are listed 'Best First'.
Re: How to store arrays in another array
by Fletch (Bishop) on Oct 03, 2019 at 18:19 UTC

    You want to store a reference to the array. $rows[0] = \@row1; or push @rows, \@row1; for example. See perlref, perldsc, perllol.

    Additionally: referencing a single element of an array with a @ sigil is (pretty much always) wrong; if you mean a single element use $foo[$idx].

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: How to store arrays in another array
by AnomalousMonk (Archbishop) on Oct 03, 2019 at 18:32 UTC

    Slightly more concise:

    c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "my @row1 = qw(71 22 15 10 51); my @row2 = qw(91 82 28 11 91); my @row3 = qw(11 72 37 58 20); my @row4 = qw(21 42 63 24 16); my @row5 = qw(81 32 53 54 42); ;; my @rows = \(@row1, @row2, @row3, @row4, @row5); ;; dd \@rows; " [ [71, 22, 15, 10, 51], [91, 82, 28, 11, 91], [11, 72, 37, 58, 20], [21, 42, 63, 24, 16], [81, 32, 53, 54, 42], ]


    Give a man a fish:  <%-{-{-{-<

Re: How to store arrays in another array
by Bloodnok (Vicar) on Oct 07, 2019 at 13:25 UTC
    ... or even more succinctly ...
    my @rows = ( [ qw(71 22 15 10 51) ], [ qw(91 82 28 11 91) ], [ qw(11 72 37 58 20) ], [ qw(21 42 63 24 16) ], [ qw(81 32 53 54 42) ], );
    or, if you really need to identify each array separately ...
    my @row1 = qw(71 22 15 10 51); my @row2 = qw(91 82 28 11 91); my @row3 = qw(11 72 37 58 20); my @row4 = qw(21 42 63 24 16); my @row5 = qw(81 32 53 54 42); my @rows = ( \@row1, \@row2, \@row3, \@row4, \@row5 );
    A user level that continues to overstate my experience :-))

      my @rows = ( \@row1, \@row2, \@row3, \@row4, \@row5 );
      That's what
          my @rows = \(@row1, @row2, @row3, @row4, @row5);
      does.


      Give a man a fish:  <%-{-{-{-<

        Hmm, never knew that; TFT - just goes to show that my sig isn't in the least inaccurate

        A user level that continues to overstate my experience :-))