Complex Data Structures
An array of hashes is simply an array whose elements are hash references — each { ... } inside the list literal creates an anonymous hash and immediately takes a reference to it. This is the idiomatic way to represent a list of records in Perl.
use strict;
use warnings;
my @people = (
{ name => "Alice", age => 30 },
{ name => "Bob", age => 25 },
);
for my $person (@people) {
print "$person->{name} is $person->{age}\n";
}
Alice is 30 Bob is 25
Each $person in the loop is a hash reference, so $person->{name} reaches into it with the same arrow from the previous lesson. The reverse shape — a hash of arrays — works the same way with [ ... ] anonymous array references as the values:
use strict;
use warnings;
my %teams = (
red => ["Alice", "Bob"],
blue => ["Carol", "Dave"],
);
for my $team (sort keys %teams) {
my @members = @{ $teams{$team} };
print "$team: @members\n";
}
blue: Carol Dave red: Alice Bob
@{ $teams{$team} } dereferences the array reference stored under each key back into a plain list. Structures like these — nesting hash refs inside array refs inside hash refs, as deep as needed — are how every non-trivial Perl program represents real data. Next: map, grep, and sort — Perl's functional list-processing idiom.
Practice exercise
Given my @items = ({ qty => 3 }, { qty => 5 }, { qty => 2 }), sum every qty and print the total.