References and Data Structures in Perl
Use references to build the structures flat arrays and hashes can't: arrays of hashes, hashes of arrays, and arbitrarily nested data.
- perl
- references
- data-structures
- intermediate
Arrays and hashes only hold scalars — so to build anything nested, you need references. A reference is a scalar that points at another value. This is the key to real data structures in Perl.
Making and using references
Put a \ in front of a variable to get a reference to it:
my @colors = ("red", "green", "blue");
my $aref = \@colors; # reference to the array
my %ages = (Ada => 36);
my $href = \%ages; # reference to the hash
Create anonymous references directly with [] and {}:
my $aref = ["red", "green", "blue"]; # anonymous array ref
my $href = { Ada => 36, Bo => 41 }; # anonymous hash ref
Dereferencing
To get back to the data, use the arrow -> for single elements:
print $aref->[0]; # red
print $href->{Ada}; # 36
To get the whole thing back:
my @all = @$aref; # or @{ $aref }
my %copy = %$href;
The arrow rule
Between two sets of brackets, the arrow is optional. These are identical:
$data->{users}[0]{name}
$data->{users}->[0]->{name}
Arrays of hashes
A common shape — a list of records:
my @people = (
{ name => "Ada", role => "eng" },
{ name => "Bo", role => "sales" },
);
for my $p (@people) {
print "$p->{name} works in $p->{role}\n";
}
Hashes of arrays
Group things under keys:
my %team = (
eng => ["Ada", "Cy"],
sales => ["Bo"],
);
push @{ $team{eng} }, "Dev"; # add to the eng list
print "eng: @{ $team{eng} }\n"; # eng: Ada Cy Dev
Nesting arbitrarily
Because a reference is just a scalar, you can nest to any depth:
my $company = {
name => "Perl Archive",
teams => {
eng => [
{ name => "Ada", langs => ["perl", "c"] },
],
},
};
print $company->{teams}{eng}[0]{langs}[0]; # perl
Inspecting a structure
When a nested structure confuses you, dump it:
use Data::Dumper;
print Dumper($company);
Where to go next
Return to the Perl Archive hub for the full set of guides, or start at the beginning with the Perl Tutorial for Beginners.