This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Teach diagnostics.pm about %p
[perl5.git] / pod / perlref.pod
index 21f15d4..5f9ce0a 100644 (file)
@@ -24,7 +24,7 @@ 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
-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
@@ -51,6 +51,19 @@ 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 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>
 
@@ -210,17 +223,18 @@ that most Perl programmers need trouble themselves about to begin with.
 =item 5.
 X<constructor> X<new>
 
-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() and called indirectly:
+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 C<new()>.  You I<can> call them
+indirectly:
 
-    $objref = new Doggie (Tail => 'short', Ears => 'long');
+    $objref = new Doggie( Tail => 'short', Ears => 'long' );
 
-But don't have to be:
+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');
 
@@ -329,7 +343,6 @@ However, a "simple scalar" includes an identifier that itself uses method
     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
@@ -366,7 +379,6 @@ called %hashref, not dereferencing through $hashref to the hash
 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
@@ -404,7 +416,6 @@ Well, okay, not entirely like C's arrays, actually.  C doesn't know how
 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
@@ -454,6 +465,64 @@ chicanery is also useful for arbitrary expressions:
 
     print "That yields @{[$n + 5]} widgets\n";
 
+Similarly, an expression that returns a reference to a scalar can be
+dereferenced via C<${...}>. Thus, the above expression may be written
+as:
+
+    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>
@@ -474,7 +543,7 @@ People frequently expect it to work like this.  So it does.
     ${$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
 
@@ -506,16 +575,16 @@ variables, which are all "global" to the package.
 
 =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";
 
@@ -523,8 +592,7 @@ and even
 
     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:
 
@@ -532,9 +600,9 @@ 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" }
 
@@ -609,16 +677,25 @@ above happens too late to be of much use.  You could address this by
 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;
@@ -635,9 +712,9 @@ A work-around is the following:
     }
 
 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.
@@ -669,5 +746,5 @@ 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
-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.