Search⌘ K

Nested Data Structures

Explore how Perl references enable the creation and manipulation of nested data structures such as arrays and hashes within arrays or hashes. Understand the role of autovivification, the use of dereferencing syntax, and strategies for managing code clarity and safety when working with complex data models.

Storing an array in an array

Perl’s aggregate data types—arrays and hashes—store scalars indexed by integer or string keys. Note the word scalar. If we try to store an array in an array, Perl’s automatic list flattening will make everything into a single array:

Perl
my @counts = qw( eenie miney moe );
my @ducks = qw( huey dewey louie );
my @game = qw( duck duck grayduck );
my @famous_triplets = (
@counts, @ducks, @game
);
say "@famous_triplets";

Use references

Perl’s solution to this is references, which are special scalars that can refer to other variables. Nested data structures in Perl, such as an array of arrays or a hash of hashes, are possible through the use of references. Unfortunately, the reference syntax isn’t the most visually appealing.

We can use the reference operator \ to produce a reference to a named variable:

Perl
my @counts = qw( eenie miney moe );
my @ducks = qw( huey dewey louie );
my @game = qw( duck duck grayduck );
my @famous_triplets = (
\@counts, \@ducks, \@game
);
say "@famous_triplets";

Alternatively, we can use the anonymous reference declaration syntax to avoid the use of named variables:

Perl
my @famous_triplets = (
[qw( eenie miney moe )],
[qw( huey dewey louie )],
[qw( duck duck goose )],
);
my %meals = (
breakfast => { entree => 'eggs',
side => 'hash browns' },
lunch => { entree => 'panini',
side => 'apple' },
dinner => { entree => 'steak',
side => 'avocado salad' },
);

Note: Perl allows an optional trailing ...