Accessing Elements in Nested Data Structures

Building nested data structures is one thing; getting elements out of them is another. With references inside arrays pointed to by other references, getting at an actual element can be a chore, particularly in complex structures. Fortunately, Perl has syntax to help.

Say you have a matrix (array of arrays) of numbers like the one we used in the last section:

@nums = (
   [ 3, 4, 2, 4, 2, 3 ],
   [ 5, 3, 2, 4, 5, 4 ],
   [ 7, 6, 3, 2, 8, 3 ],
   [ 3, 4, 7, 8, 3, 4, ],
);

Now let's say you wanted to access the fourth element of the third row. You could use standard array access to get to the third row:

$nums[2]

But that would give you a reference, not the data that reference points to (remember, you only get ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.