|
perlref - Perl references and nested data structures
This is complete documentation about all aspects of references.
For a shorter, tutorial introduction to just the essential features,
see the perlreftut manpage.
Before release 5 of Perl it was difficult to represent complex data
structures, because all references had to be symbolic--and even then
it was difficult to refer to a variable instead of a symbol table entry.
Perl now not only makes it easier to use symbolic references to variables,
but also lets you have "hard" references to any piece of data or code.
Any scalar may hold a hard reference. Because arrays and hashes contain
scalars, you can now easily build arrays of arrays, arrays of hashes,
hashes of arrays, arrays of hashes of functions, and so on.
Hard references are smart--they keep track of reference counts for you,
automatically freeing the thing referred to when its reference count goes
to zero. (Reference counts for values in self-referential or
cyclic data structures may not go to zero without a little help; see
Two-Phased Garbage Collection in the perlobj manpage for a detailed explanation.)
If that thing happens to be an object, the object is destructed. See
the perlobj manpage for more about objects. (In a sense, everything in Perl is an
object, but we usually reserve the word for references to objects that
have been officially "blessed" into a class package.)
Symbolic references are names of variables or other objects, just as a
symbolic link in a Unix filesystem contains merely the name of a file.
The *glob notation is something of a symbolic reference. (Symbolic
references are sometimes called "soft references", but please don't call
them that; references are confusing enough without useless synonyms.)
In contrast, hard references are more like hard links in a Unix file
system: They are used to access an underlying object without concern for
what its (other) name is. When the word "reference" is used without an
adjective, as in the following paragraph, it is usually talking about a
hard reference.
References are easy to use in Perl. There is just one overriding
principle: Perl does no implicit referencing or dereferencing. When a
scalar is holding a reference, it always behaves as a simple scalar. It
doesn't magically start being an array or hash or subroutine; you have to
tell it explicitly to do so, by dereferencing it.
References can be created in several ways.
-
By using the backslash operator on a variable, subroutine, or value.
(This works much like the & (address-of) operator in C.)
This typically creates another reference to a variable, because
there's already a reference to the variable in the symbol table. But
the symbol table reference might go away, and you'll still have the
reference that the backslash returned. Here are some examples:
$scalarref = \$foo;
$arrayref = \@ARGV;
$hashref = \%ENV;
$coderef = \&handler;
$globref = \*foo;
It isn't possible to create a true reference to an IO handle (filehandle
or dirhandle) using the backslash operator. The most you can get is a
reference to a typeglob, which is actually a complete symbol table entry.
But see the explanation of the *foo{THING} syntax below. However,
you can still use type globs and globrefs as though they were IO handles.
-
A reference to an anonymous array can be created using square
brackets:
$arrayref = [1, 2, ['a', 'b', 'c']];
Here we've created a reference to an anonymous array of three elements
whose final element is itself a reference to another anonymous array of three
elements. (The multidimensional syntax described later can be used to
access this. For example, after the above, $arrayref->[2][1] would have
the value "b".)
Taking a reference to an enumerated list is not the same
as using square brackets--instead it's the same as creating
a list of references!
@list = (\$a, \@b, \%c);
@list = \($a, @b, %c);
As a special case, \(@foo) returns a list of references to the contents
of @foo, not a reference to @foo itself. Likewise for %foo,
except that the key references are to copies (since the keys are just
strings rather than full-fledged scalars).
-
A reference to an anonymous hash can be created using curly
brackets:
$hashref = {
'Adam' => 'Eve',
'Clyde' => 'Bonnie',
};
Anonymous hash and array composers like these can be intermixed freely to
produce as complicated a structure as you want. The multidimensional
syntax described below works for these too. The values above are
literals, but variables and expressions would work just as well, because
assignment operators in Perl (even within local() or my()) are executable
statements, not compile-time declarations.
Because curly brackets (braces) are used for several other things
including BLOCKs, you may occasionally have to disambiguate braces at the
beginning of a statement by putting a + or a return in front so
that Perl realizes the opening brace isn't starting a BLOCK. The economy and
mnemonic value of using curlies is deemed worth this occasional extra
hassle.
For example, if you wanted a function to make a new hash and return a
reference to it, you have these options:
sub hashem { { @_ } }
sub hashem { +{ @_ } }
sub hashem { return { @_ } }
On the other hand, if you want the other meaning, you can do this:
sub showem { { @_ } }
sub showem { {; @_ } }
sub showem { { return @_ } }
The leading +{ and {; always serve to disambiguate
the expression to mean either the HASH reference, or the BLOCK.
-
A reference to an anonymous subroutine can be created by using
sub without a subname:
$coderef = sub { print "Boink!\n" };
Note the semicolon. Except for the code
inside not being immediately executed, a sub {} is not so much a
declaration as it is an operator, like do{} or eval{}. (However, no
matter how many times you execute that particular line (unless you're in an
eval("...")), $coderef will still have a reference to the same
anonymous subroutine.)
Anonymous subroutines act as closures with respect to my() variables,
that is, variables lexically visible within the current scope. Closure
is a notion out of the Lisp world that says if you define an anonymous
function in a particular lexical context, it pretends to run in that
context even when it's called outside the context.
In human terms, it's a funny way of passing arguments to a subroutine when
you define it as well as when you call it. It's useful for setting up
little bits of code to run later, such as callbacks. You can even
do object-oriented stuff with it, though Perl already provides a different
mechanism to do that--see the perlobj manpage.
You might also think of closure as a way to write a subroutine
template without using eval(). Here's a small example of how
closures work:
sub newprint {
my $x = shift;
return sub { my $y = shift; print "$x, $y!\n"; };
}
$h = newprint("Howdy");
$g = newprint("Greetings");
&$h("world");
&$g("earthlings");
This prints
Howdy, world!
Greetings, earthlings!
Note particularly that $x continues to refer to the value passed
into newprint() despite "my $x" having gone out of scope by the
time the anonymous subroutine runs. That's what a closure is all
about.
This applies only to lexical variables, by the way. Dynamic variables
continue to work as they have always worked. Closure is not something
that most Perl programmers need trouble themselves about to begin with.
-
References are often returned by special subroutines called constructors. Perl
objects are just references to a special type of object that happens to know
which package it's associated with. Constructors are just special subroutines
that know how to create that association. They do so by starting with an
ordinary reference, and it remains an ordinary reference even while it's also
being an object. Constructors are often named new(). You can call them
indirectly:
$objref = new Doggie( Tail => 'short', Ears => 'long' );
But that can produce ambiguous syntax in certain cases, so it's often
better to use the direct method invocation approach:
$objref = Doggie->new(Tail => 'short', Ears => 'long');
use Term::Cap;
$terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
use Tk;
$main = MainWindow->new();
$menubar = $main->Frame(-relief => "raised",
-borderwidth => 2)
-
References of the appropriate type can spring into existence if you
dereference them in a context that assumes they exist. Because we haven't
talked about dereferencing yet, we can't show you any examples yet.
-
A reference can be created by using a special syntax, lovingly known as
the *foo{THING} syntax. *foo{THING} returns a reference to the THING
slot in *foo (which is the symbol table entry which holds everything
known as foo).
$scalarref = *foo{SCALAR};
$arrayref = *ARGV{ARRAY};
$hashref = *ENV{HASH};
$coderef = *handler{CODE};
$ioref = *STDIN{IO};
$globref = *foo{GLOB};
$formatref = *foo{FORMAT};
All of these are self-explanatory except for *foo{IO}. It returns
the IO handle, used for file handles (open in the perlfunc manpage), sockets
(socket in the perlfunc manpage and socketpair in the perlfunc manpage), and directory
handles (opendir in the perlfunc manpage). For compatibility with previous
versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}, though it
is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn
of its use.
*foo{THING} returns undef if that particular THING hasn't been used yet,
except in the case of scalars. *foo{SCALAR} returns a reference to an
anonymous scalar if $foo hasn't been used yet. This might change in a
future release.
*foo{IO} is an alternative to the *HANDLE mechanism given in
Typeglobs and Filehandles in the perldata manpage for passing filehandles
into or out of subroutines, or storing into larger data structures.
Its disadvantage is that it won't create a new filehandle for you.
Its advantage is that you have less risk of clobbering more than
you want to with a typeglob assignment. (It still conflates file
and directory handles, though.) However, if you assign the incoming
value to a scalar instead of a typeglob as we do in the examples
below, there's no risk of that happening.
splutter(*STDOUT);
splutter(*STDOUT{IO});
sub splutter {
my $fh = shift;
print $fh "her um well a hmmm\n";
}
$rec = get_rec(*STDIN);
$rec = get_rec(*STDIN{IO});
sub get_rec {
my $fh = shift;
return scalar <$fh>;
}
That's it for creating references. By now you're probably dying to
know how to use references to get back to your long-lost data. There
are several basic methods.
-
Anywhere you'd put an identifier (or chain of identifiers) as part
of a variable or subroutine name, you can replace the identifier with
a simple scalar variable containing a reference of the correct type:
$bar = $$scalarref;
push(@$arrayref, $filename);
$$arrayref[0] = "January";
$$hashref{"KEY"} = "VALUE";
&$coderef(1,2,3);
print $globref "output\n";
It's important to understand that we are specifically not dereferencing
$arrayref[0] or $hashref{"KEY"} there. The dereference of the
scalar variable happens before it does any key lookups. Anything more
complicated than a simple scalar variable must use methods 2 or 3 below.
However, a "simple scalar" includes an identifier that itself uses method
1 recursively. Therefore, the following prints "howdy".
$refrefref = \\\"howdy";
print $$$$refrefref;
-
Anywhere you'd put an identifier (or chain of identifiers) as part of a
variable or subroutine name, you can replace the identifier with a
BLOCK returning a reference of the correct type. In other words, the
previous examples could be written like this:
$bar = ${$scalarref};
push(@{$arrayref}, $filename);
${$arrayref}[0] = "January";
${$hashref}{"KEY"} = "VALUE";
&{$coderef}(1,2,3);
$globref->print("output\n");
Admittedly, it's a little silly to use the curlies in this case, but
the BLOCK can contain any arbitrary expression, in particular,
subscripted expressions:
&{ $dispatch{$index} }(1,2,3 |