< Perl Tutorial

Perl references

← Previous Next →

Perl References

A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used. We can construct lists containing references to other lists, which can contain references to hashes, and so on. This is how the nested data structures are built in Perl.

We can also use references to create anonymous data. Anonymous data is data that doesn't have a variable name attached to it. Instead, it's placed at a certain memory location, and we're given a simple reference to that location. Our list (or hash or whatever) has no name to speak of, but we know exactly where to find it, should we need to use it.

Reference Creation

There are two ways to create a reference, one for each of the following conditions:

  1. We've already got the data in a variable.
  2. We want to use anonymous data to go straight to a reference.

For the first case, we can create a reference by simply putting a backslash in front of the variable. The following example shows how:

$scalarref = \$foo;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&handler;
$globref   = \*foo;

To get an array reference instead of an array, use square brackets [] instead of parentheses. To get a hash reference instead of a hash, use curly braces {} instead of parentheses. The following examples illustrate this:

To refer to an array reference, instead of doing this:

my @array = (1, 2, 3, 4, 5);
my $array_r = \@array;

we can do this:

my $array_r = [1, 2, 3, 4, 5];

An dto create a hash reference, instead of doing this:

my %hash = ( apple => "pomme", pear => "poire" );
my $hash_r = \%hash;

we can do this:

my $hash_r = { apple => "pomme", pear => "poire" };


Dereferencing returns the value from a reference point to the location. To dereference a reference we simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. The following example explains dereferencing:

$var = 10;

# Now $r has reference to $var scalar.
$r = \$var;

# Print value available at the location stored in $r.
print "Value of $var is : ", $$r, "\n";

@var = (1, 2, 3);
# Now $r has reference to @var array.
$r = \@var;
# Print values available at the location stored in $r.
print "Value of @var is : ",  @$r, "\n";

%var = ('key1' => 10, 'key2' => 20);
# Now $r has reference to %var hash.
$r = \%var;
# Print values available at the location stored in $r.
print "Value of %var is : ", %$r, "\n";

The above code produces the following output:

Value of 10 is : 10
Value of 1 2 3 is : 123
Value of %var is : key220key110


← Previous Next →