Common Mistakes
As mentioned earlier, Perl arrays and hashes are one-dimensional. In Perl, even “multidimensional” arrays are actually one-dimensional, but the values along that dimension are references to other arrays, which collapse many elements into one. If you print these values out without dereferencing them, you will get the stringified references rather than the data you want. For example, these two lines:
@AoA = ( [2, 3], [4, 5, 7], [0] ); print "@AoA";
result in something like:
ARRAY(0x83c38) ARRAY(0x8b194) ARRAY(0x8b1d0)
On the other hand, this line displays 7:
print $AoA[1][2];
When constructing an array of arrays, remember to compose new references for the subarrays. Otherwise, you will just create an array containing the element counts of the subarrays, like this:
for $i (1..10) {
@array = somefunc($i);
$AoA[$i] = @array; # WRONG!
}Here, @array is being
accessed in scalar context, and therefore yields the count of its
elements, which is dutifully assigned to $AoA[$i]. The proper way to assign the
reference will be shown in a moment.
After making the previous mistake people realize they need to assign a reference, so the next mistake people naturally make involves taking a reference to the same memory location over and over again:
for $i (1..10) {
@array = somefunc($i);
$AoA[$i] = \@array; # WRONG AGAIN!
}Every reference generated by the second line of the for loop is the same, namely, a reference
to the single array @array. Yes, this array changes on each pass through the loop, ...
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