Perl references and nested data structures

Arrays and hashes hold only scalars, so complex data is built from references: a reference is a scalar that points at an array, a hash, a subroutine, or another scalar. [1, 2, 3] creates a reference to a new array, {a => 1} creates a reference to a new hash, and \@list refers to an existing array. @{ $ref } turns an array reference back into the array, and $ref->[0] and $ref->{key} access single elements.

Perl
use strict;
use warnings;
use List::Util qw(sum);

my %scores = (Ada => [90, 85], Bo => [70], Cy => []);
push @{ $scores{Bo} }, 95;
$scores{Di}[0] = 60;

for my $name (sort keys %scores) {
    my @s = @{ $scores{$name} };
    my $average = @s ? sprintf("%.1f", sum(@s) / @s) : "n/a";
    print "$name: ", scalar(@s), " scores, average $average\n";
}

print join(" ", ref(\1), ref([]), ref({}), ref(sub { 1 }), ref(\\1)), "\n";

my %copy = %scores;
delete $copy{Cy};
print exists $scores{Cy} ? "Cy still in the original\n" : "Cy gone\n";
print join(",", sort keys %copy), "\n";
my @both = @scores{qw(Ada Bo)};
print scalar(@{ $both[0] }) + scalar(@{ $both[1] }), " scores for Ada and Bo\n";
Read the full lesson