Learn Perl: data structures


There's a common misconception about Perl data structures. A beginner might want to declare a multi-dimensional data structure like this:

my @array = (
        ('a', 'b', 'c'),
        ('d' => 'e'),
);

This does not work, as it creates a one-dimensional array of five elements. Refactoring it a bit does not help:

my @nested1 = ('a', 'b', 'c');
my %nested2 = ('d' => 'e');

my @array = (
        @nested1,
        %nested2
);

What's going on?

Data structures in Perl can contain a list of single (scalar) values. Arrays and hashes have multiple values and because of that they are interpolated directly into the list they're put into. If the goal is to have a multi-dimensional structure, every structure of the second dimension and above must be a reference, which is a scalar value masquerading as the original structure.

There are a couple of ways to create a reference, one is through square braces (reference to anonymous array) and curly braces (reference to anonymous hash):

my @array = (
        ['a', 'b', 'c'],
        {'d' => 'e'},
);

Another one is through backslash, the referencing operator (reference to named array or hash):

my @nested1 = ('a', 'b', 'c');
my %nested2 = ('d' => 'e');

my @array = (
        \@nested1,
        \%nested2
);

Dereferencing

If referencing turns a data structure into a scalar value, there must be a way to reverse that operation. It is called dereferencing.

The way it is most commonly done is through @{} for arrays and %{} for hashes:

my @nested1_back = @{ $array[0] };
my %nested2_back = %{ $array[1] };

There's also the arrow operator, which dereferences for the sake of getting one of the structure's values:

print (shift @array)->[0]; # prints 'a'
print (shift @array)->{d}; # prints 'e'

Referencing in Perl is crucial to become proficient with the language and to actually understand how things work. It also gives the programmer almost absolute power over the way their data is represented and passed around. I strongly recommend digging deeper into the subject with the help of following references:

Learn Perl is a series of articles targeting those who are just starting with the language. The goal is to explain some of the trickier yet commonly used parts of the syntax. See the whole series here. For a proper introduction to the language, please see the free Modern Perl book.


Comments? Suggestions? Send to feedback@bbrtj.eu
Published on 2021-05-07