home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeJava and XSLTSearch this book

4.8. References and Complex Data Structures

A Perl reference is a fundamental data type that "points" to another piece of data or code. A reference knows the location of the information and the type of data stored there.

A reference is a scalar and can be used anywhere a scalar can be used. Any array element or hash value can contain a reference (a hash key cannot contain a reference), which is how nested data structures are built in Perl. You can construct lists containing references to other lists, which can contain references to hashes, and so on.

4.8.1. Creating References

You can create a reference to an existing variable or subroutine by prefixing it with a backslash:

$a = "fondue";
@alist = ("pitt", "hanks", "cage", "cruise");
%song = ("mother" => "crying", "brother" => "dying");
sub freaky_friday { s/mother/daughter/ }
# Create references
$ra = \$a;
$ralist = \@alist;
$rsong = \%song;
$rsub = \&freaky_friday; # '&' required for subroutine names

References to scalar constants are created similarly:

$pi = \3.14159;
$myname = \"Charlie";

Note that all references are prefixed by a $, even if they refer to an array or hash. All references are scalars; thus, you can copy a reference to another scalar or even reference another reference:

$aref = \@names;
$bref = $aref;            # Both refer to @names
$cref = \$aref;           # $cref is a reference to $aref

Because arrays and hashes are collections of scalars, you can create references to individual elements by prefixing their names with backslashes:

$star = \$alist[2];       # Refers to third element of @alist
$action = \$song{mother}; # Refers to the 'mother' value of %song

4.8.2. Dereferencing

Dereferencing returns the value a reference points to. The general method of dereferencing uses the reference variable substituted for the regular name part of a variable. If $r is a reference, then $$r, @$r, or %$r retrieve the value that is referred to, depending on whether $r is pointing to a scalar, array, or hash. A reference can be used in all the places where an ordinary data type can be used.

When a reference is accidentally evaluated as a plain scalar, it returns a string that indicates the type of data it points to and the memory address of the data.

If you just want to know the type of data that is being referenced, use ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false.


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.