Complex Data Structures
Arrays and hashes can only hold scalars, but a reference is a scalar. So by storing references inside arrays and hashes you can build any shape of data: arrays of arrays, hashes of arrays, arrays of hashes, records, trees and so on.
Arrays of arrays (a table)
use strict;
use warnings;
my @matrix = (
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
);
print "Middle: $matrix[1][1]\n"; # arrow between subscripts is optional
print "Row 2: @{ $matrix[2] }\n";
for my $row (@matrix) {
print join(" ", map { sprintf "%2d", $_ * 10 } @$row), "\n";
}Middle: 5
Row 2: 7 8 9
10 20 30
40 50 60
70 80 90
$matrix[1][1] is short for $matrix[1]->[1]: between two subscripts the arrow can be left out.
Hashes of arrays
A hash whose values are array references is perfect for grouping:
use strict;
use warnings;
my %courses_of = (
ana => ["math", "art"],
ben => ["history"],
);
push @{ $courses_of{ben} }, "music";
push @{ $courses_of{cleo} }, "biology"; # autovivification creates the array
for my $student (sort keys %courses_of) {
my @list = @{ $courses_of{$student} };
printf "%-5s %d: %s\n", $student, scalar(@list), join(", ", @list);
}ana 2: math, art
ben 2: history, music
cleo 1: biology
Pushing onto @{ $courses_of{cleo} } when that key does not exist yet makes Perl create a new anonymous array automatically. This is called autovivification, and it makes building structures very convenient.
Arrays of hashes (records)
A list of records, like rows from a database, is an array of hash references:
use strict;
use warnings;
my @employees = (
{ name => "Iris", dept => "IT", salary => 5200 },
{ name => "Marco", dept => "Sales", salary => 4100 },
{ name => "Noor", dept => "IT", salary => 6100 },
);
my @it = grep { $_->{dept} eq "IT" } @employees;
print "IT staff: ", join(", ", map { $_->{name} } @it), "\n";
my %payroll;
$payroll{ $_->{dept} } += $_->{salary} for @employees;
print "$_: $payroll{$_}\n" for sort keys %payroll;
my ($top) = sort { $b->{salary} <=> $a->{salary} } @employees;
print "Highest paid: $top->{name}\n";IT staff: Iris, Noor
IT: 11300
Sales: 4100
Highest paid: Noor
Hashes of hashes and deeper nesting
use strict;
use warnings;
my %config = (
database => { host => "db.local", port => 5432 },
cache => { host => "cache.local", port => 6379, ttl => [60, 300] },
);
print "DB port: $config{database}{port}\n";
print "Long TTL: $config{cache}{ttl}[1]\n";
$config{logging}{level} = "debug"; # autovivifies $config{logging}
for my $section (sort keys %config) {
my $settings = $config{$section};
my @pairs = map { "$_=" . (ref $settings->{$_} ? "[@{ $settings->{$_} }]" : $settings->{$_}) }
sort keys %$settings;
print "[$section] @pairs\n";
}DB port: 5432
Long TTL: 300
[cache] host=cache.local port=6379 ttl=[60 300]
[database] host=db.local port=5432
[logging] level=debug
Inspecting structures with Data::Dumper
When a structure gets complicated, the core module Data::Dumper prints it as Perl code. Set Sortkeys for stable hash output and Indent = 1 for a compact layout:
use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent = 1;
my $order = {
id => 1042,
items => [ { sku => "A1", qty => 2 }, { sku => "B7", qty => 1 } ],
paid => 1,
};
print Dumper($order);$VAR1 = {
'id' => 1042,
'items' => [
{
'qty' => 2,
'sku' => 'A1'
},
{
'qty' => 1,
'sku' => 'B7'
}
],
'paid' => 1
};
Copying nested data
Copying the top level (my @copy = @matrix;) copies only the references, so the inner arrays are still shared. That is a "shallow copy":
use strict;
use warnings;
my @grid = ([1, 2], [3, 4]);
my @shallow = @grid;
$shallow[0][0] = 99;
print "After shallow change: $grid[0][0]\n";
my @deep = map { [@$_] } @grid; # copy each inner array too
$deep[1][1] = -1;
print "After deep change: $grid[1][1]\n";After shallow change: 99
After deep change: 4
For arbitrary deep copies, the core module Storable provides dclone.
Test yourself
What is $data{fruits}[2] short for?
$data{fruits}->[2]@data{fruits}[2]$data->{fruits}{2}%data[2]
What is autovivification?
- Automatic garbage collection
- Perl creating missing intermediate arrays or hashes when you use them as references
- Copying data automatically
- Sorting hash keys automatically
Why can my @copy = @nested; cause surprises?
- It deletes
@nested - It only copies the references, so inner arrays are shared
- It reverses the data
- It is a syntax error