6.2. Creating and deferencing

To create a reference to a scalar, array or hash, we prefix its name with a backslash:

my $scalar = "This is a scalar";
my @array  = qw(a b c);
my %hash   = ('sky' => 'blue', 'apple' => 'red', 'grass' => 'green');

my $scalar_ref = \$scalar;
my $array_ref  = \@array;
my $hash_ref   = \%hash;

Note that all references are scalars, because they contain a single item of information - the memory address of the actual data.

Dereferencing (getting at the value that a reference points to) is achieved by prepending the appropriate variable-type punctuation to the name of the reference. For instance, if we have a hash reference $hash_reference we can dereference it by looking for %$hash_reference.

my $new_scalar = $$scalar_ref;
my @new_array  = @$array_ref;
my %new_hash   = %$hash_ref;

In other words, wherever you would normally put a variable name (like new_scalar) you can put a reference variable (like $scalar_ref).

Here's how you access array elements or slices, and hash elements:

print $$array_ref[0];           # prints the first element of the array
                                # referenced by $array_ref
print $$array_ref[0-2];         # prints an array slice
print $$hash_ref{'sky'};        # prints a hash element's value

The other way to access the value that a reference points to is using the "arrow" notation. This notation is usually considered to be better Perl style than the one shown above, which can have precedence problems and is less visually clean.

print $array_ref->[0];
print $hash_ref->{'sky'};

Readme: The Panther book describes a good way to visualise this method. Ask your instructor to demonstrate it or to loan you a copy of the book if you need a better understanding of the above syntax.