This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Promote v5.36 usage and feature bundles doc
[perl5.git] / pod / perlref.pod
index a165dbc..2fd321b 100644 (file)
@@ -51,21 +51,12 @@ 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.
+=head3 Backslash Operator
 X<\> X<backslash>
 
 By using the backslash operator on a variable, subroutine, or value.
@@ -87,7 +78,7 @@ reference to a typeglob, which is actually a complete symbol table entry.
 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.
+=head3 Square Brackets
 X<array, anonymous> X<[> X<[]> X<square bracket>
 X<bracket, square> X<arrayref> X<array reference> X<reference, array>
 
@@ -107,14 +98,14 @@ as using square brackets--instead it's the same as creating
 a list of references!
 
     @list = (\$a, \@b, \%c);
-    @list = \($a, @b, %c);     # same thing!
+    @list = \($a, @b, %c);      # same thing!
 
 As a special case, C<\(@foo)> returns a list of references to the contents
 of C<@foo>, not a reference to C<@foo> itself.  Likewise for C<%foo>,
 except that the key references are to copies (since the keys are just
 strings rather than full-fledged scalars).
 
-=item 3.
+=head3 Curly Brackets
 X<hash, anonymous> X<{> X<{}> X<curly bracket>
 X<bracket, curly> X<brace> X<hashref> X<hash reference> X<reference, hash>
 
@@ -122,8 +113,8 @@ A reference to an anonymous hash can be created using curly
 brackets:
 
     $hashref = {
-       'Adam'  => 'Eve',
-       'Clyde' => 'Bonnie',
+        'Adam'  => 'Eve',
+        'Clyde' => 'Bonnie',
     };
 
 Anonymous hash and array composers like these can be intermixed freely to
@@ -157,7 +148,7 @@ On the other hand, if you want the other meaning, you can do this:
 The leading C<+{> and C<{;> always serve to disambiguate
 the expression to mean either the HASH reference, or the BLOCK.
 
-=item 4.
+=head3 Anonymous Subroutines
 X<subroutine, anonymous> X<subroutine, reference> X<reference, subroutine>
 X<scope, lexical> X<closure> X<lexical> X<lexical scope>
 
@@ -190,8 +181,8 @@ 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"; };
+        my $x = shift;
+        return sub { my $y = shift; print "$x, $y!\n"; };
     }
     $h = newprint("Howdy");
     $g = newprint("Greetings");
@@ -215,7 +206,7 @@ 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.
 
-=item 5.
+=head3 Constructors
 X<constructor> X<new>
 
 References are often returned by special subroutines called constructors.  Perl
@@ -241,14 +232,19 @@ better to use the direct method invocation approach:
     $menubar = $main->Frame(-relief              => "raised",
                             -borderwidth         => 2)
 
-=item 6.
+This indirect object syntax is only available when
+L<C<use feature "indirect">|feature/The 'indirect' feature> is in effect,
+and that is not the case when L<C<use v5.36>|perlfunc/use VERSION> (or
+higher) is requested, it is best to avoid indirect object syntax entirely.
+
+=head3 Autovivification
 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.
+=head3 Typeglob Slots
 X<*foo{THING}> X<*>
 
 A reference can be created by using a special syntax, lovingly known as
@@ -272,8 +268,9 @@ 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}>, though it
-is deprecated as of 5.8.0.  If deprecation warnings are in effect, it will warn
-of its use.
+is discouraged, to encourage a consistent use of one name: IO.  On perls
+between v5.8 and v5.22, it will issue a deprecation warning, but this
+deprecation has since been rescinded.
 
 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
@@ -297,24 +294,22 @@ 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);         # pass the whole glob
-    splutter(*STDOUT{IO});     # pass both file and dir handles
+    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";
+        my $fh = shift;
+        print $fh "her um well a hmmm\n";
     }
 
-    $rec = get_rec(*STDIN);    # pass the whole glob
+    $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;
-       return scalar <$fh>;
+        my $fh = shift;
+        return scalar <$fh>;
     }
 
-=back
-
 =head2 Using References
 X<reference, use> X<dereferencing> X<dereference>
 
@@ -322,9 +317,7 @@ 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.
 
-=over 4
-
-=item 1.
+=head3 Simple Scalar
 
 Anywhere you'd put an identifier (or chain of identifiers) as part
 of a variable or subroutine name, you can replace the identifier with
@@ -347,7 +340,7 @@ However, a "simple scalar" includes an identifier that itself uses method
     $refrefref = \\\"howdy";
     print $$$$refrefref;
 
-=item 2.
+=head3 Block
 
 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
@@ -365,7 +358,7 @@ 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);     # call correct routine
+    &{ $dispatch{$index} }(1,2,3);      # call correct routine
 
 Because of being able to omit the curlies for the simple case of C<$$x>,
 people often make the mistake of viewing the dereferencing symbols as
@@ -374,16 +367,16 @@ though, you could use parentheses instead of braces.  That's not the case.
 Consider the difference below; case 0 is a short-hand version of case 1,
 I<not> case 2:
 
-    $$hashref{"KEY"}   = "VALUE";      # CASE 0
-    ${$hashref}{"KEY"} = "VALUE";      # CASE 1
-    ${$hashref{"KEY"}} = "VALUE";      # CASE 2
-    ${$hashref->{"KEY"}} = "VALUE";    # CASE 3
+    $$hashref{"KEY"}   = "VALUE";       # CASE 0
+    ${$hashref}{"KEY"} = "VALUE";       # CASE 1
+    ${$hashref{"KEY"}} = "VALUE";       # CASE 2
+    ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
 
 Case 2 is also deceptive in that you're accessing a variable
 called %hashref, not dereferencing through $hashref to the hash
 it's presumably referencing.  That would be case 3.
 
-=item 3.
+=head3 Arrow Notation
 
 Subroutine calls and lookups of individual array elements arise often
 enough that it gets cumbersome to use method 2.  As a form of
@@ -420,7 +413,7 @@ multidimensional arrays just like C's:
 Well, okay, not entirely like C's arrays, actually.  C doesn't know how
 to grow its arrays on demand.  Perl does.
 
-=item 4.
+=head3 Objects
 
 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
@@ -430,7 +423,7 @@ encapsulation without a very good reason.  Perl does not enforce
 encapsulation.  We are not totalitarians here.  We do expect some basic
 civility though.
 
-=back
+=head3 Miscellaneous Usage
 
 Using a string or number as a reference produces a symbolic reference,
 as explained above.  Using a reference as a number produces an
@@ -440,7 +433,7 @@ 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";
+        print "refs 1 and 2 refer to the same thing\n";
     }
 
 Using a reference as a string produces both its referent's type,
@@ -505,7 +498,8 @@ 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.
+L<Scalar::Util> module, or available as C<builtin::weaken> directly in
+Perl version 5.35.7 or later.
 
 Here's how we can make the first example safer:
 
@@ -543,14 +537,14 @@ value.
 People frequently expect it to work like this.  So it does.
 
     $name = "foo";
-    $$name = 1;                        # Sets $foo
-    ${$name} = 2;              # Sets $foo
-    ${$name x 2} = 3;          # Sets $foofoo
-    $name->[0] = 4;            # Sets $foo[0]
-    @$name = ();               # Clears @foo
-    &$name();                  # Calls &foo()
+    $$name = 1;                 # Sets $foo
+    ${$name} = 2;               # Sets $foo
+    ${$name x 2} = 3;           # Sets $foofoo
+    $name->[0] = 4;             # Sets $foo[0]
+    @$name = ();                # Clears @foo
+    &$name();                   # Calls &foo()
     $pack = "THAT";
-    ${"${pack}::$name"} = 5;   # Sets $THAT::foo without eval
+    ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
 
 This is powerful, and slightly dangerous, in that it's possible
 to intend (with the utmost sincerity) to use a hard reference, and
@@ -571,8 +565,8 @@ a symbol table, and thus are invisible to this mechanism.  For example:
     local $value = 10;
     $ref = "value";
     {
-       my $value = 20;
-       print $$ref;
+        my $value = 20;
+        print $$ref;
     }
 
 This will still print 10, not 20.  Remember that local() affects package
@@ -602,30 +596,30 @@ construct is I<not> considered to be a symbolic reference when you're
 using strict refs:
 
     use strict 'refs';
-    ${ bareword };     # Okay, means $bareword.
-    ${ "bareword" };   # Error, symbolic reference.
+    ${ bareword };      # Okay, means $bareword.
+    ${ "bareword" };    # Error, symbolic reference.
 
 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" }
+    $hash{ "aaa" }{ "bbb" }{ "ccc" }
 
 you can write just
 
-    $array{ aaa }{ bbb }{ ccc }
+    $hash{ aaa }{ bbb }{ ccc }
 
 and not worry about whether the subscripts are reserved words.  In the
 rare event that you do wish to do something like
 
-    $array{ shift }
+    $hash{ shift }
 
 you can force interpretation as a reserved word by adding anything that
 makes it more than a bareword:
 
-    $array{ shift() }
-    $array{ +shift }
-    $array{ shift @_ }
+    $hash{ shift() }
+    $hash{ +shift }
+    $hash{ shift @_ }
 
 The C<use warnings> pragma or the B<-w> switch will warn you if it
 interprets a reserved word as a string.
@@ -659,7 +653,7 @@ trying to build.
 
     @colors = qw(red blue green yellow orange purple violet);
     for my $name (@colors) {
-        no strict 'refs';      # allow symbol table manipulation
+        no strict 'refs';       # allow symbol table manipulation
         *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
     }
 
@@ -724,27 +718,7 @@ 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:
-
-    $x{ \$a } = $a;
-
-If you try to dereference the key, it won't do a hard dereference, and
-you won't accomplish what you're attempting.  You might want to do something
-more like
-
-    $r = \@a;
-    $x{ $r } = $r;
-
-And then at least you can use the values(), which will be
-real refs, instead of the keys(), which won't.
-
-The standard Tie::RefHash module provides a convenient workaround to this.
-
-=head1 Postfix Dereference Syntax
+=head2 Postfix Dereference Syntax
 
 Beginning in v5.20.0, a postfix syntax for using references is
 available.  It behaves as described in L</Using References>, but instead
@@ -758,9 +732,9 @@ For example:
     $r = [ 1, [ 2, 3 ], 4 ];
     $r->[1]->@*;  # equivalent to @{ $r->[1] }
 
-This syntax must be enabled with C<use feature 'postderef'>.  It is
-experimental, and will warn by default unless C<no warnings
-'experimental::postderef'> is in effect.
+In Perl 5.20 and 5.22, this syntax must be enabled with C<use feature
+'postderef'>. As of Perl 5.24, no feature declarations are required to make
+it available.
 
 Postfix dereference should work in all circumstances where block
 (circumfix) dereference worked, and should be entirely equivalent.  This
@@ -783,7 +757,7 @@ Glob elements can be extracted through the postfix dereferencing feature:
 
 Postfix array and scalar dereferencing I<can> be used in interpolating
 strings (double quotes or the C<qq> operator), but only if the
-additional C<postderef_qq> feature is enabled.
+C<postderef_qq> feature is enabled.
 
 =head2 Postfix Reference Slicing
 
@@ -802,9 +776,9 @@ Slices">, also behaves as expected:
 
 As with postfix array, postfix value slice dereferencing I<can> be used
 in interpolating strings (double quotes or the C<qq> operator), but only
-if the additional C<postderef_qq> L<feature> is enabled.
+if the C<postderef_qq> L<feature> is enabled.
 
-=head1 Assigning to References
+=head2 Assigning to References
 
 Beginning in v5.22.0, the referencing operator can be assigned to.  It
 performs an aliasing operation, so that the variable name referenced on the
@@ -874,7 +848,7 @@ Combining that form with C<local> and putting parentheses immediately
 around a hash are forbidden (because it is not clear what they should do):
 
     \local(@array) = foo(); # WRONG
-    \(%hash)       = bar(); # wRONG
+    \(%hash)       = bar(); # WRONG
 
 Assignment to references and non-references may be combined in lists and
 conditional ternary expressions, as long as the values on the right-hand
@@ -887,7 +861,7 @@ for obfuscated code:
     # @harry is (1,2,3)
 
     my $type = ref $thingy;
-    ($type ? $type == 'ARRAY' ? \@foo : \$bar : $baz) = $thingy;
+    ($type ? $type eq 'ARRAY' ? \@foo : \$bar : $baz) = $thingy;
 
 The C<foreach> loop can also take a reference constructor for its loop
 variable, though the syntax is limited to one of the following, with an
@@ -906,7 +880,7 @@ arrays-of-arrays, or arrays-of-hashes:
     }
 
     foreach \my %h (@array_of_hashes) {
-        $h{gelastic}++ if $h{type} == 'funny';
+        $h{gelastic}++ if $h{type} eq 'funny';
     }
 
 B<CAVEAT:> Aliasing does not work correctly with closures.  If you try to
@@ -915,6 +889,49 @@ will only be visible within that inner sub, and will not affect the outer
 subroutine where the variables are declared.  This bizarre behavior is
 subject to change.
 
+=head2 Declaring a Reference to a Variable
+
+Beginning in v5.26.0, the referencing operator can come after C<my>,
+C<state>, C<our>, or C<local>.  This syntax must be enabled with C<use
+feature 'declared_refs'>.  It is experimental, and will warn by default
+unless C<no warnings 'experimental::refaliasing'> is in effect.
+
+This feature makes these:
+
+    my \$x;
+    our \$y;
+
+equivalent to:
+
+    \my $x;
+    \our $x;
+
+It is intended mainly for use in assignments to references (see
+L</Assigning to References>, above).  It also allows the backslash to be
+used on just some items in a list of declared variables:
+
+    my ($foo, \@bar, \%baz); # equivalent to:  my $foo, \my(@bar, %baz);
+
+=head1 WARNING: Don't use references as hash keys
+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:
+
+    $x{ \$a } = $a;
+
+If you try to dereference the key, it won't do a hard dereference, and
+you won't accomplish what you're attempting.  You might want to do something
+more like
+
+    $r = \@a;
+    $x{ $r } = $r;
+
+And then at least you can use the values(), which will be
+real refs, instead of the keys(), which won't.
+
+The standard Tie::RefHash module provides a convenient workaround to this.
+
 =head1 SEE ALSO
 
 Besides the obvious documents, source code can be instructive.