Nested Data Structures
Recall that arrays and hashes contain only scalars; they cannot directly contain another array or hash as such. But considering that references can refer to an array or a hash and that references are scalars, you can see how one or more elements in an array or hash can point to other arrays or hashes. In this section, we will study how to build nested, heterogeneous data structures.
Let us say we would like to track a person’s details and that of their dependents. One approach is to create separate named hash tables for each person:
%sue = ( # Parent
'name' => 'Sue',
'age' => '45');
%john = ( # Child
'name' => 'John',
'age' => '20');
%peggy = ( # Child
'name' => 'Peggy',
'age' => '16');The structures for John and Peggy can now be related to Sue like this:
@children = (\%john, \%peggy);
$sue{'children'} = \@children;
# Or
$sue{'children'} = [\%john, \%peggy];Figure 1.2 shows this structure after it has been built.

Figure 1-2. Mixing scalars with arrays and hashes.
This is how you can print Peggy’s age, given
%sue:
print $sue{children}->[1]->{age};Implicit Creation of Complex Structures
Suppose the first line in your program is this:
$sue{children}->[1]->{age} = 10;Perl automatically creates the hash %sue, gives it
a hash element indexed by the string children, points that entry to a newly allocated array, whose second element is made to refer to a freshly allocated ...
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