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
-L<perlobj/"Two-Phased Garbage Collection"> for a detailed explanation.)
+L</"Circular References"> for a detailed explanation.)
If that thing happens to be an object, the object is destructed. See
L<perlobj> for more about objects. (In a sense, everything in Perl is an
object, but we usually reserve the word for references to objects that
doesn't magically start being an array or hash or subroutine; you have to
tell it explicitly to do so, by dereferencing it.
+References are easy to use in Perl. There is just one overriding
+principle: in general, 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.
+
+That said, be aware that Perl version 5.14 introduces an exception
+to the rule, for syntactic convenience. Experimental array and hash container
+function behavior allows array and hash references to be handled by Perl as
+if they had been explicitly syntactically dereferenced. See
+L<perl5140delta/"Syntactical Enhancements">
+and L<perlfunc> for details.
+
=head2 Making References
X<reference, creation> X<referencing>
print $$$$refrefref;
=item 2.
-X<${}> X<@{}> X<%{}>
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
it's presumably referencing. That would be case 3.
=item 3.
-X<autovivification> X<< -> >> X<arrow>
Subroutine calls and lookups of individual array elements arise often
enough that it gets cumbersome to use method 2. As a form of
to grow its arrays on demand. Perl does.
=item 4.
-X<encapsulation>
If a reference happens to be a reference to an object, then there are
probably methods to access the things referred to, and you should probably
print "That yields ${\($n + 5)} widgets\n";
+=head2 Circular References
+X<circular reference> X<reference, circular>
+
+It is possible to create a "circular reference" in Perl, which can lead
+to memory leaks. A circular reference occurs when two references
+contain a reference to each other, like this:
+
+ my $foo = {};
+ my $bar = { foo => $foo };
+ $foo->{bar} = $bar;
+
+You can also create a circular reference with a single variable:
+
+ my $foo;
+ $foo = \$foo;
+
+In this case, the reference count for the variables will never reach 0,
+and the references will never be garbage-collected. This can lead to
+memory leaks.
+
+Because objects in Perl are implemented as references, it's possible to
+have circular references with objects as well. Imagine a TreeNode class
+where each node references its parent and child nodes. Any node with a
+parent will be part of a circular reference.
+
+You can break circular references by creating a "weak reference". A
+weak reference does not increment the reference count for a variable,
+which means that the object can go out of scope and be destroyed. You
+can weaken a reference with the C<weaken> function exported by the
+L<Scalar::Util> module.
+
+Here's how we can make the first example safer:
+
+ use Scalar::Util 'weaken';
+
+ my $foo = {};
+ my $bar = { foo => $foo };
+ $foo->{bar} = $bar;
+
+ weaken $foo->{bar};
+
+The reference from C<$foo> to C<$bar> has been weakened. When the
+C<$bar> variable goes out of scope, it will be garbage-collected. The
+next time you look at the value of the C<< $foo->{bar} >> key, it will
+be C<undef>.
+
+This action at a distance can be confusing, so you should be careful
+with your use of weaken. You should weaken the reference in the
+variable that will go out of scope I<first>. That way, the longer-lived
+variable will contain the expected reference until it goes out of
+scope.
+
=head2 Symbolic references
X<reference, symbolic> X<reference, soft>
X<symbolic reference> X<soft reference>
${$name x 2} = 3; # Sets $foofoo
$name->[0] = 4; # Sets $foo[0]
@$name = (); # Clears @foo
- &$name(); # Calls &foo() (as in Perl 4)
+ &$name(); # Calls &foo()
$pack = "THAT";
${"${pack}::$name"} = 5; # Sets $THAT::foo without eval
=head2 Not-so-symbolic references
-A new feature contributing to readability in perl version 5.001 is that the
-brackets around a symbolic reference behave more like quotes, just as they
-always have within a string. That is,
+Brackets around a symbolic reference can simply
+serve to isolate an identifier or variable name from the rest of an
+expression, just as they always have within a string. For example,
$push = "pop on ";
print "${push}over";
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
+a reserved word. This is generalized to work the same
+without the enclosing double quotes, so that
print ${push} . "over";
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.) This
+will have the same effect. This
construct is I<not> considered to be a symbolic reference when you're
using strict refs:
${ bareword }; # Okay, means $bareword.
${ "bareword" }; # Error, symbolic reference.
-Similarly, because of all the subscripting that is done using single
-words, we've applied the same rule to any bareword that is used for
-subscripting a hash. So now, instead of writing
+Similarly, because of all the subscripting that is done using single words,
+the same rule applies to any bareword that is used for subscripting a hash.
+So now, instead of writing
$array{ "aaa" }{ "bbb" }{ "ccc" }
putting the whole loop of assignments within a BEGIN block, forcing it
to occur during compilation.
-Access to lexicals that change over type--like those in the C<for> loop
-above--only works with closures, not general subroutines. In the general
-case, then, named subroutines do not nest properly, although anonymous
-ones do. Thus is because named subroutines are created (and capture any
-outer lexicals) only once at compile time, whereas anonymous subroutines
-get to capture each time you execute the 'sub' operator. 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 type of thing incurs mysterious warnings about
-"will not stay shared". For example, this won't work:
+Access to lexicals that change over time--like those in the C<for> loop
+above, basically aliases to elements from the surrounding lexical scopes--
+only works with anonymous subs, not with named subroutines. Generally
+said, named subroutines do not nest properly and should only be declared
+in the main package scope.
+
+This is because named subroutines are created at compile time so their
+lexical variables get assigned to the parent lexicals from the first
+execution of the parent block. If a parent scope is entered a second
+time, its lexicals are created again, while the nested subs still
+reference the old ones.
+
+Anonymous subroutines get to capture each time you execute the C<sub>
+operator, as they are created on the fly. 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 type of thing incurs mysterious warnings about "will not stay
+shared" due to the reasons explained above.
+For example, this won't work:
sub outer {
my $x = $_[0] + 35;
}
Now inner() can only be called from within outer(), because of the
-temporary assignments of the closure (anonymous subroutine). But when
-it does, it has normal access to the lexical variable $x from the scope
-of outer().
+temporary assignments of the anonymous subroutine. But when it does,
+it has normal access to the lexical variable $x from the scope of
+outer() at the time outer is invoked.
This has the interesting effect of creating a function local to another
function, something not normally supported in Perl.
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
-complex data structures, and L<perltoot>, L<perlobj>, and L<perlbot>
+complex data structures, and L<perlootut> and L<perlobj>
for how to use them to create objects.