Creating and dereferencing references

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.

This is what a reference looks like if you print it out:

% perl -e 'my $foo_ref = \$foo; print "$foo_ref\n";'
SCALAR(0x80c697c)
% perl -e 'my $bar_ref = \@bar; print "$bar_ref\n";'
ARRAY(0x80c6988)
% perl -e 'my $baz_ref = \%baz; print "$baz_ref\n";'
HASH(0x80c6988)

You can find out whether a scalar is a reference or not by using the ref() function, which returns a string indicating the type of reference, or undef if a scalar is not a reference..

The ref() function is documented on page 204 of the Camel book or in perldoc -f ref.

Dereferencing (getting at the actual data 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 to use 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'};

The above arrow notation is best explained in the book Advanced Perl Programming. Your instructor should have a copy if you are interested.