AnyCompiler

References

Scalars, arrays, and hashes are all flat — an array can't directly contain another array as one of its elements. To build anything nested, Perl uses references: a reference is a scalar value that points at another variable. \@array takes a reference to an array, \%hash to a hash, \$scalar to a scalar — the backslash is the "take a reference to" operator, mirroring the sigils it's applied to.

use strict;
use warnings;

my @array = (1, 2, 3);
my %hash  = (a => 1, b => 2);

my $aref = \@array;
my $href = \%hash;

print "First via ref: ", $aref->[0], "\n";
print "Value via ref: ", $href->{a}, "\n";
print "Dereferenced array: @{$aref}\n";
Output
First via ref: 1
Value via ref: 1
Dereferenced array: 1 2 3

$aref->[0] and $href->{a} are the dereferencing arrows — they reach through a reference to get at an element or a value, the same way -> reaches through a pointer in C or C++. @{$aref} dereferences the whole thing back into a list. ref() tells you what kind of thing a reference points at:

use strict;
use warnings;

my $x = 10;
my $sref = \$x;
$$sref = 20;
print "x is now: $x\n";
print "Scalar ref: ", ref($sref), "\n";

my @arr = (1, 2, 3);
my $aref = \@arr;
print "Array ref: ", ref($aref), "\n";

my %h = (a => 1);
my $href = \%h;
print "Hash ref: ", ref($href), "\n";
Output
x is now: 20
Scalar ref: SCALAR
Array ref: ARRAY
Hash ref: HASH

$$sref dereferences a scalar reference directly (there's no arrow form for a single scalar the way there is for array/hash elements) — assigning through it, $$sref = 20, changes $x itself, since $sref doesn't hold a copy, it holds a pointer to $x's actual storage. Next: complex data structures — putting references to work building an array of hashes.

Practice exercise

Given my @arr = (10, 20, 30) and my $ref = \@arr, print the second element using the reference ($ref->[1]).