References and nested data

Build hashes of arrays and lists of hashes with references: [...], {...}, -> and postfix dereference ->@*.

Runs in Zerethon IDE · Perl 5.40 Official Perl documentation ↗

An array or hash can only hold scalars, so nested data is built from references: [ ... ] makes a reference to a new array, { ... } to a new hash. Follow a reference with ->.

main.pl
use v5.40;

my %classes = (
    math    => ["ada", "alan"],
    physics => ["grace"],
);
push $classes{physics}->@*, "linus";
for my $subject (sort keys %classes) {
    my @students = $classes{$subject}->@*;
    say "$subject: ", join(", ", @students), " (", scalar @students, ")";
}

my @people = ({ name => "bob", age => 25 }, { name => "amy", age => 31 });
say join " ", map { $_->{name} } sort { $b->{age} <=> $a->{age} } @people;

my $point = { x => 1, y => 2 };
$point->{z} = 3;
say join " ", map { "$_=$point->{$_}" } sort keys %$point;

my @matrix = ([1, 2], [3, 4]);
say $matrix[1][0];
say ref($point), " ", ref(\@matrix), " ", ref(sub { });

Output

math: ada, alan (2)
physics: grace, linus (2)
amy bob
x=1 y=2 z=3
3
HASH ARRAY CODE
  • \@array and \%hash take a reference to an existing variable; pass references to give a sub more than one list.
  • $ref->@* and $ref->%* give the whole array or hash back; @$ref and %$ref are the older spelling.
  • ref($x) tells what a reference points to (ARRAY, HASH, CODE), or is empty for a plain value.