Skip to content
References
step 1/5

Reading — step 1 of 5

Learn

~1 min readReferences and Structures

Perl arrays and hashes can't directly nest — @a = @b copies values. To build nested structures, use references (Perl's pointers).

Take a reference with \:

my @arr = (1, 2, 3);
my $aref = \@arr;          # reference to array

my %hash = (a => 1, b => 2);
my $href = \%hash;          # reference to hash

Anonymous references with [ ] (array) and { } (hash):

my $aref = [1, 2, 3];                       # anon arrayref
my $href = { name => "Ada", age => 36 };   # anon hashref

Dereference with ->[] (array element) and ->{} (hash value):

print $aref->[0];          # 1
print $href->{name};        # "Ada"

for my $x (@$aref) { ... }  # whole array
for my $k (keys %$href) { ... }

The arrow -> between operations on a chain is optional:

$matrix->[0]->[0]    # equivalent to:
$matrix->[0][0]

Nested structures:

my $users = [
    { name => "Ada",  age => 36 },
    { name => "Bob",  age => 25 },
];

$users->[0]{name}            # "Ada"

for my $u (@$users) {
    print "$u->{name}: $u->{age}\n";
}

This is how Perl scripts model JSON-like data, configuration trees, etc.

Data::Dumper for inspection:

use Data::Dumper;
print Dumper($users);

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…