Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

Understanding references is vital to work with complex data structures; that's the reason for this short introduction.

A reference is basically a pointer to another object. It's as simple as that.

A very important fact is that these pointers are stored in scalar variables. As hashes and arrays are basically collections of scalar variables, you can have array or hash elements that are in fact references to other structures; this way you can easily construct structures like array of arrays, array of hashes, etc.

REFERENCE TYPES

There are two types of references:

1. Symbolic reference

A symbolic reference is a pointer to the name of a variable.

For example, in the following code:

$var2 = "test message";
 
$var1 = "var2";
 
print "Contents of var2 is $$var1\n";

$var2 is a symbolic reference to a variable named $var2; you can access the data contained in $var2 using $var1 prepending a dollar sign to $var1.
 
NOTES:

  • Symbolic references don't work with lexical variables (variables defined with the keyword "my").
  • Symbolic references are dangerous (in the sense that they can introduce subtle bugs in the code). Only use them if you know what you're doing
  • To disable symbolic references, use use strict 'refs' in your code

2. Hard reference

A hard reference is a pointer to the data contained in a variable.

CREATING HARD REFERENCES

To assign a hard reference to an object to a variable, you just need to prepend a backslash to the object being referenced. Here are some examples:

$scalar_ref = $var;
$array_ref = \@array;
$hash_ref = \%hash;
$glob_ref = \*glob;

You can also assign references to objects that are not stored in any variable (anonymous objects). For example:

- Anonymous arrays (use square brackets):

$array_ref = [ "one", "two", "three" ];

- Anonymous hashes (use curly braces):

$hash_ref = { 'January' => 31, 'February' => 28 };

- Anonymous subroutines (don't specify a name after sub keyword):

$sub_ref = sub { print "Hello Perl!\n" };

DEREFERENCING

To obtain the data referenced by a variable, prepend the expected data type symbol to the reference. For example:

$array_ref = [ "one", "two", "three" ];
 
#-- use '@$array_ref' to access the array referenced by '$array_ref'
foreach ( @$array_ref )
{
  print "Value: $_\n";
}

To access the individual elements of anonymous objects, use the arrow notation (->), like in these examples:

$hash_ref = { 'January' => 31, 'February' => 28 };
$array_ref = [ "one", "two", "three" ];
 
#-- get the value of key 'January'
$num_days = $hash_ref->{'January'};
 
#-- get the second element of the array
$element = $array_ref->[1];