in reply to Multi-Dimensional Arrays and Array References

Here are some more examples for you...
#!/usr/bin/perl use strict; use warnings; # simple 1D arrays: my @rowx = (1,2,3,4); my @rowy = qw (a b c); # A 2D array is an array of references to 1D arrays: # Note that Perl 2D arrays do not need to have the same # number of elements on each row! my @twoD = (\@rowx, \@rowy); foreach my $rowref (@twoD) { print "@$rowref\n"; } # prints # 1 2 3 4 # a b c # this can be a bit confusing... # In the first print, Perl knows that $twoD[0][1] means # an array element of @twoD, not be confused with # perhaps a simple scalar of the same name! # # In the second print, we get the value of $twoD, # a simple scalar my $twoD = "asdf"; print "$twoD[0][1]\n"; # prints 2 print "$twoD\n"; # prints asdf # In general, DO NOT use the same variable name for # two different sigils! Many things are "legal" in Perl # that you should not do!
Update: You will notice that in my foreach loop, I used the name "rowref" instead of just "row". Perl wouldn't care. But naming the iteration variable like this helps me to remind myself to dereference that thing. YMMV.

Replies are listed 'Best First'.
Re^2: Multi-Dimensional Arrays and Array References
by GrandFather (Saint) on Nov 17, 2020 at 00:28 UTC
    Note that Perl 2D arrays do not need to have the same number of elements on each row!

    nor even the same type of data:

    use strict; use warnings; package PrintMe; use overload '""' => sub {return $_[0]{str};}; sub new { return bless {str => $_[1]}, $_[0]; } package main; my @mixedTable = ( [1 .. 5], {a => 1, b => 2, wibble => 'plop'}, PrintMe->new("The quick brown fox") ); for my $row (@mixedTable) { if ('ARRAY' eq ref $row) { print "@$row\n"; } elsif ('HASH' eq ref $row) { print join ', ', map{"$_ => $row->{$_}"} sort keys %$row; print "\n"; } else { print "$row\n"; } }

    Prints:

    1 2 3 4 5 a => 1, b => 2, wibble => plop The quick brown fox
    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond