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. (Note: the reference counts for values in self-referential or
+to zero. (Reference counts for values in self-referential or
cyclic data structures may not go to zero without a little help; see
L<perlobj/"Two-Phased Garbage Collection"> for a detailed explanation.)
If that thing happens to be an object, the object is destructed. See
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 C<*glob> notation is a kind of symbolic reference. (Symbolic
+The C<*glob> notation is something of a of symbolic reference. (Symbolic
references are sometimes called "soft references", but please don't call
them that; references are confusing enough without useless synonyms.)
=item 1.
By using the backslash operator on a variable, subroutine, or value.
-(This works much like the & (address-of) operator in C.) Note
-that this typically creates I<another> reference to a variable, because
+(This works much like the & (address-of) operator in C.)
+This typically creates I<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:
access this. For example, after the above, C<$arrayref-E<gt>[2][1]> would have
the value "b".)
-Note that taking a reference to an enumerated list is not the same
+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!
sub showem { {; @_ } } # ok
sub showem { { return @_ } } # ok
-Note how the leading C<+{> and C<{;> always serve to disambiguate
+The leading C<+{> and C<{;> always serve to disambiguate
the expression to mean either the HASH reference, or the BLOCK.
=item 4.
$coderef = sub { print "Boink!\n" };
-Note the presence of the semicolon. Except for the fact that the code
-inside isn't executed immediately, a C<sub {}> is not so much a
+Note the semicolon. Except for the code
+inside not being immediately executed, a C<sub {}> is not so much a
declaration as it is an operator, like C<do{}> or C<eval{}>. (However, no
matter how many times you execute that particular line (unless you're in an
C<eval("...")>), $coderef will still have a reference to the I<same>
anonymous subroutine.)
Anonymous subroutines act as closures with respect to my() variables,
-that is, variables visible lexically within the current scope. Closure
+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 of the context.
+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
do object-oriented stuff with it, though Perl already provides a different
mechanism to do that--see L<perlobj>.
-You can also think of closure as a way to write a subroutine template without
-using eval. (In fact, in version 5.000, eval was the I<only> way to get
-closures. You may wish to use "require 5.001" if you use closures.)
-
-Here's a small example of how closures works:
+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;
Howdy, world!
Greetings, earthlings!
-Note particularly that $x continues to refer to the value passed into
-newprint() I<despite> the fact that the "my $x" has seemingly gone out of
-scope by the time the anonymous subroutine runs. That's what closure
-is all about.
+Note particularly that $x continues to refer to the value passed
+into newprint() I<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
=item 5.
References are often returned by special subroutines called constructors.
-Perl objects are just references to a special kind of object that happens to know
+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
$ioref = *STDIN{IO};
$globref = *foo{GLOB};
-All of these are self-explanatory except for *foo{IO}. It returns the
-IO handle, used for file handles (L<perlfunc/open>), sockets
-(L<perlfunc/socket> and L<perlfunc/socketpair>), and directory handles
-(L<perlfunc/opendir>). For compatibility with previous versions of
-Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}.
+All of these are self-explanatory except for C<*foo{IO}>. It returns
+the IO handle, used for file handles (L<perlfunc/open>), sockets
+(L<perlfunc/socket> and L<perlfunc/socketpair>), and directory
+handles (L<perlfunc/opendir>). For compatibility with previous
+versions of Perl, C<*foo{FILEHANDLE}> is a synonym for C<*foo{IO}>.
-*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
+C<*foo{THING}> returns undef if that particular THING hasn't been used yet,
+except in the case of scalars. C<*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
+C<*foo{IO}> is an alternative to the C<*HANDLE> mechanism given in
L<perldata/"Typeglobs and Filehandles"> 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 no risk of clobbering more than you want
-to with a typeglob assignment, although if you assign to a scalar instead
-of a typeglob, you're ok.
+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});
+ splutter(*STDOUT); # pass the whole glob
+ splutter(*STDOUT{IO}); # pass both file and dir handles
sub splutter {
my $fh = shift;
print $fh "her um well a hmmm\n";
}
- $rec = get_rec(*STDIN);
- $rec = get_rec(*STDIN{IO});
+ $rec = get_rec(*STDIN); # pass the whole glob
+ $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
sub get_rec {
my $fh = shift;
=back
-The ref() operator may be used to determine what type of thing the
-reference is pointing to. See L<perlfunc>.
+Using a string or number as a reference produces a symbolic reference,
+as explained above. Using a reference as a number produces an
+integer representing its storage location in memory. The only
+useful thing to be done with this is to compare two references
+numerically to see whether they refer to the same location.
+
+ if ($ref1 == $ref2) { # cheap numeric compare of references
+ print "refs 1 and 2 refer to the same thing\n";
+ }
+
+Using a reference as a string produces both its referent's type,
+including any package blessing as described in L<perlobj>, as well
+as the numeric address expressed in hex. The ref() operator returns
+just the type of thing the reference is pointing to, without the
+address. See L<perlfunc/ref> for details and examples of its use.
The bless() operator may be used to associate the object a reference
points to with a package functioning as an object class. See L<perlobj>.
A typeglob may be dereferenced the same way a reference can, because
-the dereference syntax always indicates the kind of reference desired.
+the dereference syntax always indicates the type of reference desired.
So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
Here's a trick for interpolating a subroutine call into a string:
We said that references spring into existence as necessary if they are
undefined, but we didn't say what happens if a value used as a
reference is already defined, but I<isn't> a hard reference. If you
-use it as a reference in this case, it'll be treated as a symbolic
+use it as a reference, it'll be treated as a symbolic
reference. That is, the value of the scalar is taken to be the I<name>
of a variable, rather than a direct link to a (possibly) anonymous
value.
$pack = "THAT";
${"${pack}::$name"} = 5; # Sets $THAT::foo without eval
-This is very powerful, and slightly dangerous, in that it's possible
+This is powerful, and slightly dangerous, in that it's possible
to intend (with the utmost sincerity) to use a hard reference, and
accidentally use a symbolic reference instead. To protect against
that, you can say
$push = "pop on ";
print "${push}over";
-has always meant to print "pop on over", despite the fact that push is
+has always meant to print "pop on over", even though push is
a reserved word. This has been generalized to work the same outside
of quotes, so that
print ${ push } . "over";
will have the same effect. (This would have been a syntax error in
-Perl 5.000, though Perl 4 allowed it in the spaceless form.) Note that this
+Perl 5.000, though Perl 4 allowed it in the spaceless form.) This
construct is I<not> considered to be a symbolic reference when you're
using strict refs:
=head2 Pseudo-hashes: Using an array as a hash
-WARNING: This section describes an experimental feature. Details may
+B<WARNING>: This section describes an experimental feature. Details may
change without notice in future versions.
-Beginning with release 5.005 of Perl you can use an array reference
+Beginning with release 5.005 of Perl, you may use an array reference
in some contexts that would normally require a hash reference. This
allows you to access array elements using symbolic names, as if they
were fields in a structure.
do the translation from field names to array indices at compile time for
typed object references. See L<fields>.
-
=head2 Function Templates
As explained above, a closure is an anonymous function with access to the
print "Be ", red("careful"), "with that ", green("light");
-The red() and green() functions would be very similar. To create these,
+The red() and green() functions would be similar. To create these,
we'll assign a closure to a typeglob of the name of the function we're
trying to build.
case, then, named subroutines do not nest properly, although anonymous
ones do. If you are accustomed to using nested subroutines in other
programming languages with their own private variables, you'll have to
-work at it a bit in Perl. The intuitive coding of this kind of thing
+work at it a bit in Perl. The intuitive coding of this type of thing
incurs mysterious warnings about ``will not stay shared''. For example,
this won't work:
=head1 SEE ALSO
Besides the obvious documents, source code can be instructive.
-Some rather pathological examples of the use of references can be found
+Some pathological examples of the use of references can be found
in the F<t/op/ref.t> regression test in the Perl source directory.
See also L<perldsc> and L<perllol> for how to use references to create