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

Get Perl in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.