This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update IO-Compress to CPAN version 2.040
[perl5.git] / pod / perlref.pod
index 08a2b42..0fab809 100644 (file)
@@ -1,4 +1,5 @@
 =head1 NAME
+X<reference> X<pointer> X<data structure> X<structure> X<struct>
 
 perlref - Perl references and nested data structures
 
@@ -23,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
@@ -31,15 +32,18 @@ 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 C<*glob> notation is something of a of symbolic reference.  (Symbolic
+The C<*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.)
+X<reference, symbolic> X<reference, soft>
+X<symbolic reference> X<soft reference>
 
 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.
+X<reference, hard> X<hard reference>
 
 References are easy to use in Perl.  There is just one overriding
 principle: Perl does no implicit referencing or dereferencing.  When a
@@ -47,13 +51,28 @@ 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>
 
 References can be created in several ways.
 
 =over 4
 
 =item 1.
+X<\> X<backslash>
 
 By using the backslash operator on a variable, subroutine, or value.
 (This works much like the & (address-of) operator in C.)  
@@ -75,6 +94,8 @@ But see the explanation of the C<*foo{THING}> syntax below.  However,
 you can still use type globs and globrefs as though they were IO handles.
 
 =item 2.
+X<array, anonymous> X<[> X<[]> X<square bracket>
+X<bracket, square> X<arrayref> X<array reference> X<reference, array>
 
 A reference to an anonymous array can be created using square
 brackets:
@@ -84,7 +105,7 @@ brackets:
 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, C<$arrayref-E<gt>[2][1]> would have
+access this.  For example, after the above, C<< $arrayref->[2][1] >> would have
 the value "b".)
 
 Taking a reference to an enumerated list is not the same
@@ -100,6 +121,8 @@ except that the key references are to copies (since the keys are just
 strings rather than full-fledged scalars).
 
 =item 3.
+X<hash, anonymous> X<{> X<{}> X<curly bracket>
+X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash>
 
 A reference to an anonymous hash can be created using curly
 brackets:
@@ -140,6 +163,8 @@ The leading C<+{> and C<{;> always serve to disambiguate
 the expression to mean either the HASH reference, or the BLOCK.
 
 =item 4.
+X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine>
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
 
 A reference to an anonymous subroutine can be created by using
 C<sub> without a subname:
@@ -196,18 +221,20 @@ continue to work as they have always worked.  Closure is not something
 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');
 
@@ -220,12 +247,14 @@ But don't have to be:
                             -borderwidth         => 2)
 
 =item 6.
+X<autovivification>
 
 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.
 
 =item 7.
+X<*foo{THING}> X<*>
 
 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
@@ -238,12 +267,15 @@ known as foo).
     $coderef   = *handler{CODE};
     $ioref     = *STDIN{IO};
     $globref   = *foo{GLOB};
+    $formatref = *foo{FORMAT};
 
 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}>.
+versions of Perl, C<*foo{FILEHANDLE}> is a synonym for C<*foo{IO}>, though it
+is deprecated as of 5.8.0.  If deprecation warnings are in effect, it will warn
+of its use.
 
 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
@@ -279,6 +311,7 @@ below, there's no risk of that happening.
 =back
 
 =head2 Using References
+X<reference, use> X<dereferencing> X<dereference>
 
 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
@@ -357,7 +390,7 @@ syntactic sugar, the examples for method 2 may be written:
 
 The left side of the arrow can be any expression returning a reference,
 including a previous dereference.  Note that C<$array[$x]> is I<not> the
-same thing as C<$array-E<gt>[$x]> here:
+same thing as C<< $array->[$x] >> here:
 
     $array[$x]->{"foo"}->[0] = "January";
 
@@ -365,7 +398,7 @@ This is one of the cases we mentioned earlier in which references could
 spring into existence when in an lvalue context.  Before this
 statement, C<$array[$x]> may have been undefined.  If so, it's
 automatically defined with a hash reference so that we can look up
-C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
+C<{"foo"}> in it.  Likewise C<< $array[$x]->{"foo"} >> will automatically get
 defined with an array reference so that we can look up C<[0]> in it.
 This process is called I<autovivification>.
 
@@ -399,6 +432,7 @@ 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.
+X<reference, numeric context>
 
     if ($ref1 == $ref2) {  # cheap numeric compare of references
        print "refs 1 and 2 refer to the same thing\n";
@@ -409,6 +443,7 @@ 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.
+X<reference, string context>
 
 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>.
@@ -430,7 +465,67 @@ 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>
 
 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
@@ -480,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,
+Since Perl verion 5.001, 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.  In 5.001, this was generalized to work the same
+without the enclosing double quotes, so that
 
     print ${push} . "over";
 
@@ -506,9 +601,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" }
 
@@ -528,66 +623,25 @@ makes it more than a bareword:
     $array{ +shift }
     $array{ shift @_ }
 
-The B<-w> switch will warn you if it interprets a reserved word as a string.
+The C<use warnings> pragma or the B<-w> switch will warn you if it
+interprets a reserved word as a string.
 But it will no longer warn you about using lowercase words, because the
 string is effectively quoted.
 
 =head2 Pseudo-hashes: Using an array as a hash
+X<pseudo-hash> X<pseudo hash> X<pseudohash>
 
-B<WARNING>:  This section describes an experimental feature.  Details may
-change without notice in future versions.
-
-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.
-
-For this to work, the array must contain extra information.  The first
-element of the array has to be a hash reference that maps field names
-to array indices.  Here is an example:
-
-   $struct = [{foo => 1, bar => 2}, "FOO", "BAR"];
-
-   $struct->{foo};  # same as $struct->[1], i.e. "FOO"
-   $struct->{bar};  # same as $struct->[2], i.e. "BAR"
-
-   keys %$struct;   # will return ("foo", "bar") in some order
-   values %$struct; # will return ("FOO", "BAR") in same some order
-
-   while (my($k,$v) = each %$struct) {
-       print "$k => $v\n";
-   }
-
-Perl will raise an exception if you try to delete keys from a pseudo-hash
-or try to access nonexistent fields.  For better performance, Perl can also
-do the translation from field names to array indices at compile time for
-typed object references.  See L<fields>.
-
-There are two ways to check for the existance of a key in a
-pseudo-hash.  The first is to use exists().  This checks to see if the
-given field has been used yet.  It acts this way to match the behavior
-of a regular hash.  For instance:
-
-       $phash = [{foo =>, bar => 2, pants => 3}, 'FOO'];
-       $phash->{pants} = undef;
-
-       exists $phash->{foo};    # true, 'foo' was set in the declaration
-       exists $phash->{bar};    # false, 'bar' has not been used.
-       exists $phash->{pants};  # true, your 'pants' have been touched
-
-The second is to use exists() on the hash reference sitting in the
-first array element.  This checks to see if the given key is a valid
-field in the pseudo-hash.
-
-       exists $phash->[0]{pants};      # true, 'pants' is a valid field
-       exists $phash->[0]{shoes};      # false, 'shoes' can't be used
+Pseudo-hashes have been removed from Perl.  The 'fields' pragma
+remains available.
 
 =head2 Function Templates
+X<scope, lexical> X<closure> X<lexical> X<lexical scope>
+X<subroutine, nested> X<sub, nested> X<subroutine, local> X<sub, local>
 
-As explained above, a closure is an anonymous function with access to the
-lexical variables visible when that function was compiled.  It retains
-access to those variables even though it doesn't get run until later,
-such as in a signal handler or a Tk callback.
+As explained above, an anonymous function with access to the lexical
+variables visible when that function was compiled, creates a closure.  It
+retains access to those variables even though it doesn't get run until
+later, such as in a signal handler or a Tk callback.
 
 Using a closure as a function template allows us to generate many functions
 that act similarly.  Suppose you wanted functions named after the colors
@@ -624,20 +678,31 @@ 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.  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;
         sub inner { return $x * 19 }   # WRONG
         return $x + inner();
-    } 
+    }
 
 A work-around is the following:
 
@@ -645,17 +710,18 @@ A work-around is the following:
         my $x = $_[0] + 35;
         local *inner = sub { return $x * 19 };
         return $x + inner();
-    } 
+    }
 
 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.
 
 =head1 WARNING
+X<reference, string context> X<reference, use as hash key>
 
 You may not (usefully) use a reference as the key to a hash.  It will be
 converted into a string:
@@ -681,5 +747,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.