Perl Language Variables Array References


Example

Array References are scalars ($) which refer to Arrays.

my @array = ("Hello"); # Creating array, assigning value from a list
my $array_reference = \@array;

These can be created more short-hand as follows:

my $other_array_reference = ["Hello"];

Modifying / Using array references require dereferencing them first.

my @contents = @{ $array_reference };               # Prefix notation
my @contents = @$array_reference;                   # Braces can be left out
5.24.0

New postfix dereference syntax, available by default from v5.24

use v5.24;
my @contents = $array_reference->@*; # New postfix notation 

When accessing an arrayref's contents by index you can use the -> syntactical sugar.

my @array = qw(one two three);      my $arrayref = [ qw(one two three) ]
my $one = $array[0];                my $one = $arrayref->[0];

Unlike arrays, arrayrefs can be nested:

my @array = ( (1, 0), (0, 1) )  # ONE array of FOUR elements: (1, 0, 0, 1)
my @matrix = ( [1, 0], [0, 1] ) # an array of two arrayrefs
my $matrix = [ [0, 1], [1, 0] ] # an arrayref of arrayrefs
# There is no namespace conflict between scalars, arrays and hashes
# so @matrix and $matrix _both_ exist at this point and hold different values.

my @diagonal_1 = ($matrix[0]->[1], $matrix[1]->[0])     # uses @matrix
my @diagonal_2 = ($matrix->[0]->[1], $matrix->[1]->[0]) # uses $matrix
# Since chained []- and {}-access can only happen on references, you can
# omit some of those arrows.
my $corner_1 = $matrix[0][1];   # uses @matrix;
my $corner_2 = $matrix->[0][1]; # uses $matrix;  

When used as Boolean, references are always true.