← Back to Perl Course | Chapter 6: References | Lesson 4 of 7

Nested data structures

References let you put arrays inside hashes and hashes inside arrays to model real data.

In this page:

  1. Nested data structures

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

perl
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
Common Mistakes
  1. Forgetting that each level is a reference and needs its own subscript
  2. Being surprised when reading a nested key creates the parent levels
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.