Access and Printing
Now let’s print the data structure. If you only want one element, this is sufficient:
print $AoA[3][2];
But if you want to print the whole thing, you can’t just say:
print @AoA; # WRONG
It’s wrong because you’ll see stringified references instead
of your data. Perl never automatically dereferences for you.
Instead, you have to roll yourself a loop or two. The following code
prints the whole structure, looping through the elements of @AoA and dereferencing each inside the
say statement:
for $row ( @AoA ) {
say "@$row";
}If you want to keep track of subscripts, you might do this:
for $i ( 0 .. $#AoA ) {
say "row $i is: @{$AoA[$i]}";
}or maybe even this (notice the inner loop):
for $i ( 0 .. $#AoA ) {
for $j ( 0 .. $#{$AoA[$i]} ) {
say "element $i $j is $AoA[$i][$j]";
}
}As you can see, things are getting a bit complicated. That’s why sometimes it’s easier to use a temporary variable on your way through:
for $i ( 0 .. $#AoA ) {
$row = $AoA[$i];
for $j ( 0 .. $#{$row} ) {
say "element $i $j is $row–>[$j]";
}
}When you get tired of writing a custom print for your data
structures, you might look at the standard Dumpvalue or Data::Dumper modules. The former is what the Perl debugger uses,
while the latter generates parsable Perl code. For example:
use v5.14; # using the + prototype, new to v5.14 sub show(+) { require Dumpvalue; state $prettily = new Dumpvalue:: tick => q("), compactDump => 1, # comment these two lines out veryCompact => 1, # if you want a bigger dump ; dumpValue ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access