Creating References

There are several ways to create references, most of which we will describe before explaining how to use (dereference) the resulting references.

The Backslash Operator

You can create a reference to any named variable or subroutine with a backslash. (You may also use it on an anonymous scalar value like 7 or "camel", although you won't often need to.) This operator works like the & (address-of) operator in C--at least at first glance.

Here are some examples:

$scalarref = \$foo;
$constref  = \186_282.42;
$arrayref  = \@ARGV;
$hashref   = \%ENV;
$coderef   = \&handler;
$globref   = \*STDOUT;

The backslash operator can do more than produce a single reference. It will generate a whole list of references if applied to a list. See Section 8.3.6 for details.

Anonymous Data

In the examples just shown, the backslash operator merely makes a duplicate of a reference that is already held in a variable name--with one exception. The 186_282.42 isn't referenced by a named variable--it's just a value. It's one of those anonymous referents we mentioned earlier. Anonymous referents are accessed only through references. This one happens to be a number, but you can create anonymous arrays, hashes, and subroutines as well.

The anonymous array composer

You can create a reference to an anonymous array with square brackets:

$arrayref = [1, 2, ['a', 'b', 'c', 'd']];

Here we've composed an anonymous array of three elements, whose final element is a reference to an anonymous array of four elements (depicted ...

Get Programming Perl, 3rd 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.