Nested data structures
References let you put arrays inside hashes and hashes inside arrays to model real data.
In this page:
Nested data structures
Because array and hash elements are scalars, they can hold references to other arrays and hashes. Perl lets you omit arrows between subscripts, so $data->{users}[0]{name} reaches deep into the structure. Assigning to a deep path creates the intermediate levels automatically, which is called autovivification.
Note:
exists on a deep path will autovivify the parts above it, so test each level if that matters.
Example: Nested data structures
use strict;
use warnings;
my %school = (
name => "Perl High",
classes => [
{ subject => "Math", students => ["Ann", "Ben"] },
{ subject => "Science", students => ["Cy"] },
],
);
print "school: $school{name}\n";
print "first subject: $school{classes}[0]{subject}\n";
print "second student: $school{classes}->[0]->{students}->[1]\n";
for my $class (@{ $school{classes} }) {
printf "%s has %d student(s): %s\n", $class->{subject}, scalar @{ $class->{students} }, join(", ", @{ $class->{students} });
}
$school{teachers}{math}{count} = 3;
print "teachers keys: ", join(",", sort keys %{ $school{teachers} }), "\n";
# Output:
# school: Perl High
# first subject: Math
# second student: Ben
# Math has 2 student(s): Ann, Ben
# Science has 1 student(s): Cy
# teachers keys: math
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that each level is a reference and needs its own subscript
- Being surprised when reading a nested key creates the parent levels
- Using parentheses instead of brackets for an inner list
Chapter Summary
- Elements can hold references
- Arrows between subscripts are optional
- Deep assignment autovivifies levels
- Use [ ] and { } for inner structures
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: