1PERLREF(1)             Perl Programmers Reference Guide             PERLREF(1)
2
3
4

NAME

6       perlref - Perl references and nested data structures
7

NOTE

9       This is complete documentation about all aspects of references.  For a
10       shorter, tutorial introduction to just the essential features, see
11       perlreftut.
12

DESCRIPTION

14       Before release 5 of Perl it was difficult to represent complex data
15       structures, because all references had to be symbolic--and even then it
16       was difficult to refer to a variable instead of a symbol table entry.
17       Perl now not only makes it easier to use symbolic references to
18       variables, but also lets you have "hard" references to any piece of
19       data or code.  Any scalar may hold a hard reference.  Because arrays
20       and hashes contain scalars, you can now easily build arrays of arrays,
21       arrays of hashes, hashes of arrays, arrays of hashes of functions, and
22       so on.
23
24       Hard references are smart--they keep track of reference counts for you,
25       automatically freeing the thing referred to when its reference count
26       goes to zero.  (Reference counts for values in self-referential or
27       cyclic data structures may not go to zero without a little help; see
28       "Circular References" for a detailed explanation.)  If that thing
29       happens to be an object, the object is destructed.  See perlobj for
30       more about objects.  (In a sense, everything in Perl is an object, but
31       we usually reserve the word for references to objects that have been
32       officially "blessed" into a class package.)
33
34       Symbolic references are names of variables or other objects, just as a
35       symbolic link in a Unix filesystem contains merely the name of a file.
36       The *glob notation is something of a symbolic reference.  (Symbolic
37       references are sometimes called "soft references", but please don't
38       call them that; references are confusing enough without useless
39       synonyms.)
40
41       In contrast, hard references are more like hard links in a Unix file
42       system: They are used to access an underlying object without concern
43       for what its (other) name is.  When the word "reference" is used
44       without an adjective, as in the following paragraph, it is usually
45       talking about a hard reference.
46
47       References are easy to use in Perl.  There is just one overriding
48       principle: in general, Perl does no implicit referencing or
49       dereferencing.  When a scalar is holding a reference, it always behaves
50       as a simple scalar.  It doesn't magically start being an array or hash
51       or subroutine; you have to tell it explicitly to do so, by
52       dereferencing it.
53
54   Making References
55       References can be created in several ways.
56
57       Backslash Operator
58
59       By using the backslash operator on a variable, subroutine, or value.
60       (This works much like the & (address-of) operator in C.)  This
61       typically creates another reference to a variable, because there's
62       already a reference to the variable in the symbol table.  But the
63       symbol table reference might go away, and you'll still have the
64       reference that the backslash returned.  Here are some examples:
65
66           $scalarref = \$foo;
67           $arrayref  = \@ARGV;
68           $hashref   = \%ENV;
69           $coderef   = \&handler;
70           $globref   = \*foo;
71
72       It isn't possible to create a true reference to an IO handle
73       (filehandle or dirhandle) using the backslash operator.  The most you
74       can get is a reference to a typeglob, which is actually a complete
75       symbol table entry.  But see the explanation of the *foo{THING} syntax
76       below.  However, you can still use type globs and globrefs as though
77       they were IO handles.
78
79       Square Brackets
80
81       A reference to an anonymous array can be created using square brackets:
82
83           $arrayref = [1, 2, ['a', 'b', 'c']];
84
85       Here we've created a reference to an anonymous array of three elements
86       whose final element is itself a reference to another anonymous array of
87       three elements.  (The multidimensional syntax described later can be
88       used to access this.  For example, after the above, "$arrayref->[2][1]"
89       would have the value "b".)
90
91       Taking a reference to an enumerated list is not the same as using
92       square brackets--instead it's the same as creating a list of
93       references!
94
95           @list = (\$a, \@b, \%c);
96           @list = \($a, @b, %c);      # same thing!
97
98       As a special case, "\(@foo)" returns a list of references to the
99       contents of @foo, not a reference to @foo itself.  Likewise for %foo,
100       except that the key references are to copies (since the keys are just
101       strings rather than full-fledged scalars).
102
103       Curly Brackets
104
105       A reference to an anonymous hash can be created using curly brackets:
106
107           $hashref = {
108               'Adam'  => 'Eve',
109               'Clyde' => 'Bonnie',
110           };
111
112       Anonymous hash and array composers like these can be intermixed freely
113       to produce as complicated a structure as you want.  The
114       multidimensional syntax described below works for these too.  The
115       values above are literals, but variables and expressions would work
116       just as well, because assignment operators in Perl (even within local()
117       or my()) are executable statements, not compile-time declarations.
118
119       Because curly brackets (braces) are used for several other things
120       including BLOCKs, you may occasionally have to disambiguate braces at
121       the beginning of a statement by putting a "+" or a "return" in front so
122       that Perl realizes the opening brace isn't starting a BLOCK.  The
123       economy and mnemonic value of using curlies is deemed worth this
124       occasional extra hassle.
125
126       For example, if you wanted a function to make a new hash and return a
127       reference to it, you have these options:
128
129           sub hashem {        { @_ } }   # silently wrong
130           sub hashem {       +{ @_ } }   # ok
131           sub hashem { return { @_ } }   # ok
132
133       On the other hand, if you want the other meaning, you can do this:
134
135           sub showem {        { @_ } }   # ambiguous (currently ok,
136                                          # but may change)
137           sub showem {       {; @_ } }   # ok
138           sub showem { { return @_ } }   # ok
139
140       The leading "+{" and "{;" always serve to disambiguate the expression
141       to mean either the HASH reference, or the BLOCK.
142
143       Anonymous Subroutines
144
145       A reference to an anonymous subroutine can be created by using "sub"
146       without a subname:
147
148           $coderef = sub { print "Boink!\n" };
149
150       Note the semicolon.  Except for the code inside not being immediately
151       executed, a "sub {}" is not so much a declaration as it is an operator,
152       like "do{}" or "eval{}".  (However, no matter how many times you
153       execute that particular line (unless you're in an eval("...")),
154       $coderef will still have a reference to the same anonymous subroutine.)
155
156       Anonymous subroutines act as closures with respect to my() variables,
157       that is, variables lexically visible within the current scope.  Closure
158       is a notion out of the Lisp world that says if you define an anonymous
159       function in a particular lexical context, it pretends to run in that
160       context even when it's called outside the context.
161
162       In human terms, it's a funny way of passing arguments to a subroutine
163       when you define it as well as when you call it.  It's useful for
164       setting up little bits of code to run later, such as callbacks.  You
165       can even do object-oriented stuff with it, though Perl already provides
166       a different mechanism to do that--see perlobj.
167
168       You might also think of closure as a way to write a subroutine template
169       without using eval().  Here's a small example of how closures work:
170
171           sub newprint {
172               my $x = shift;
173               return sub { my $y = shift; print "$x, $y!\n"; };
174           }
175           $h = newprint("Howdy");
176           $g = newprint("Greetings");
177
178           # Time passes...
179
180           &$h("world");
181           &$g("earthlings");
182
183       This prints
184
185           Howdy, world!
186           Greetings, earthlings!
187
188       Note particularly that $x continues to refer to the value passed into
189       newprint() despite "my $x" having gone out of scope by the time the
190       anonymous subroutine runs.  That's what a closure is all about.
191
192       This applies only to lexical variables, by the way.  Dynamic variables
193       continue to work as they have always worked.  Closure is not something
194       that most Perl programmers need trouble themselves about to begin with.
195
196       Constructors
197
198       References are often returned by special subroutines called
199       constructors.  Perl objects are just references to a special type of
200       object that happens to know which package it's associated with.
201       Constructors are just special subroutines that know how to create that
202       association.  They do so by starting with an ordinary reference, and it
203       remains an ordinary reference even while it's also being an object.
204       Constructors are often named new().  You can call them indirectly:
205
206           $objref = new Doggie( Tail => 'short', Ears => 'long' );
207
208       But that can produce ambiguous syntax in certain cases, so it's often
209       better to use the direct method invocation approach:
210
211           $objref   = Doggie->new(Tail => 'short', Ears => 'long');
212
213           use Term::Cap;
214           $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
215
216           use Tk;
217           $main    = MainWindow->new();
218           $menubar = $main->Frame(-relief              => "raised",
219                                   -borderwidth         => 2)
220
221       This indirect object syntax is only available when "use feature
222       "indirect"" is in effect, and that is not the case when "use v5.36" (or
223       higher) is requested, it is best to avoid indirect object syntax
224       entirely.
225
226       Autovivification
227
228       References of the appropriate type can spring into existence if you
229       dereference them in a context that assumes they exist.  Because we
230       haven't talked about dereferencing yet, we can't show you any examples
231       yet.
232
233       Typeglob Slots
234
235       A reference can be created by using a special syntax, lovingly known as
236       the *foo{THING} syntax.  *foo{THING} returns a reference to the THING
237       slot in *foo (which is the symbol table entry which holds everything
238       known as foo).
239
240           $scalarref = *foo{SCALAR};
241           $arrayref  = *ARGV{ARRAY};
242           $hashref   = *ENV{HASH};
243           $coderef   = *handler{CODE};
244           $ioref     = *STDIN{IO};
245           $globref   = *foo{GLOB};
246           $formatref = *foo{FORMAT};
247           $globname  = *foo{NAME};    # "foo"
248           $pkgname   = *foo{PACKAGE}; # "main"
249
250       Most of these are self-explanatory, but *foo{IO} deserves special
251       attention.  It returns the IO handle, used for file handles ("open" in
252       perlfunc), sockets ("socket" in perlfunc and "socketpair" in perlfunc),
253       and directory handles ("opendir" in perlfunc).  For compatibility with
254       previous versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO},
255       though it is discouraged, to encourage a consistent use of one name:
256       IO.  On perls between v5.8 and v5.22, it will issue a deprecation
257       warning, but this deprecation has since been rescinded.
258
259       *foo{THING} returns undef if that particular THING hasn't been used
260       yet, except in the case of scalars.  *foo{SCALAR} returns a reference
261       to an anonymous scalar if $foo hasn't been used yet.  This might change
262       in a future release.
263
264       *foo{NAME} and *foo{PACKAGE} are the exception, in that they return
265       strings, rather than references.  These return the package and name of
266       the typeglob itself, rather than one that has been assigned to it.  So,
267       after "*foo=*Foo::bar", *foo will become "*Foo::bar" when used as a
268       string, but *foo{PACKAGE} and *foo{NAME} will continue to produce
269       "main" and "foo", respectively.
270
271       *foo{IO} is an alternative to the *HANDLE mechanism given in "Typeglobs
272       and Filehandles" in perldata for passing filehandles into or out of
273       subroutines, or storing into larger data structures.  Its disadvantage
274       is that it won't create a new filehandle for you.  Its advantage is
275       that you have less risk of clobbering more than you want to with a
276       typeglob assignment.  (It still conflates file and directory handles,
277       though.)  However, if you assign the incoming value to a scalar instead
278       of a typeglob as we do in the examples below, there's no risk of that
279       happening.
280
281           splutter(*STDOUT);          # pass the whole glob
282           splutter(*STDOUT{IO});      # pass both file and dir handles
283
284           sub splutter {
285               my $fh = shift;
286               print $fh "her um well a hmmm\n";
287           }
288
289           $rec = get_rec(*STDIN);     # pass the whole glob
290           $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
291
292           sub get_rec {
293               my $fh = shift;
294               return scalar <$fh>;
295           }
296
297   Using References
298       That's it for creating references.  By now you're probably dying to
299       know how to use references to get back to your long-lost data.  There
300       are several basic methods.
301
302       Simple Scalar
303
304       Anywhere you'd put an identifier (or chain of identifiers) as part of a
305       variable or subroutine name, you can replace the identifier with a
306       simple scalar variable containing a reference of the correct type:
307
308           $bar = $$scalarref;
309           push(@$arrayref, $filename);
310           $$arrayref[0] = "January";
311           $$hashref{"KEY"} = "VALUE";
312           &$coderef(1,2,3);
313           print $globref "output\n";
314
315       It's important to understand that we are specifically not dereferencing
316       $arrayref[0] or $hashref{"KEY"} there.  The dereference of the scalar
317       variable happens before it does any key lookups.  Anything more
318       complicated than a simple scalar variable must use methods 2 or 3
319       below.  However, a "simple scalar" includes an identifier that itself
320       uses method 1 recursively.  Therefore, the following prints "howdy".
321
322           $refrefref = \\\"howdy";
323           print $$$$refrefref;
324
325       Block
326
327       Anywhere you'd put an identifier (or chain of identifiers) as part of a
328       variable or subroutine name, you can replace the identifier with a
329       BLOCK returning a reference of the correct type.  In other words, the
330       previous examples could be written like this:
331
332           $bar = ${$scalarref};
333           push(@{$arrayref}, $filename);
334           ${$arrayref}[0] = "January";
335           ${$hashref}{"KEY"} = "VALUE";
336           &{$coderef}(1,2,3);
337           $globref->print("output\n");  # iff IO::Handle is loaded
338
339       Admittedly, it's a little silly to use the curlies in this case, but
340       the BLOCK can contain any arbitrary expression, in particular,
341       subscripted expressions:
342
343           &{ $dispatch{$index} }(1,2,3);      # call correct routine
344
345       Because of being able to omit the curlies for the simple case of $$x,
346       people often make the mistake of viewing the dereferencing symbols as
347       proper operators, and wonder about their precedence.  If they were,
348       though, you could use parentheses instead of braces.  That's not the
349       case.  Consider the difference below; case 0 is a short-hand version of
350       case 1, not case 2:
351
352           $$hashref{"KEY"}   = "VALUE";       # CASE 0
353           ${$hashref}{"KEY"} = "VALUE";       # CASE 1
354           ${$hashref{"KEY"}} = "VALUE";       # CASE 2
355           ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
356
357       Case 2 is also deceptive in that you're accessing a variable called
358       %hashref, not dereferencing through $hashref to the hash it's
359       presumably referencing.  That would be case 3.
360
361       Arrow Notation
362
363       Subroutine calls and lookups of individual array elements arise often
364       enough that it gets cumbersome to use method 2.  As a form of syntactic
365       sugar, the examples for method 2 may be written:
366
367           $arrayref->[0] = "January";   # Array element
368           $hashref->{"KEY"} = "VALUE";  # Hash element
369           $coderef->(1,2,3);            # Subroutine call
370
371       The left side of the arrow can be any expression returning a reference,
372       including a previous dereference.  Note that $array[$x] is not the same
373       thing as "$array->[$x]" here:
374
375           $array[$x]->{"foo"}->[0] = "January";
376
377       This is one of the cases we mentioned earlier in which references could
378       spring into existence when in an lvalue context.  Before this
379       statement, $array[$x] may have been undefined.  If so, it's
380       automatically defined with a hash reference so that we can look up
381       "{"foo"}" in it.  Likewise "$array[$x]->{"foo"}" will automatically get
382       defined with an array reference so that we can look up "[0]" in it.
383       This process is called autovivification.
384
385       One more thing here.  The arrow is optional between brackets
386       subscripts, so you can shrink the above down to
387
388           $array[$x]{"foo"}[0] = "January";
389
390       Which, in the degenerate case of using only ordinary arrays, gives you
391       multidimensional arrays just like C's:
392
393           $score[$x][$y][$z] += 42;
394
395       Well, okay, not entirely like C's arrays, actually.  C doesn't know how
396       to grow its arrays on demand.  Perl does.
397
398       Objects
399
400       If a reference happens to be a reference to an object, then there are
401       probably methods to access the things referred to, and you should
402       probably stick to those methods unless you're in the class package that
403       defines the object's methods.  In other words, be nice, and don't
404       violate the object's encapsulation without a very good reason.  Perl
405       does not enforce encapsulation.  We are not totalitarians here.  We do
406       expect some basic civility though.
407
408       Miscellaneous Usage
409
410       Using a string or number as a reference produces a symbolic reference,
411       as explained above.  Using a reference as a number produces an integer
412       representing its storage location in memory.  The only useful thing to
413       be done with this is to compare two references numerically to see
414       whether they refer to the same location.
415
416           if ($ref1 == $ref2) {  # cheap numeric compare of references
417               print "refs 1 and 2 refer to the same thing\n";
418           }
419
420       Using a reference as a string produces both its referent's type,
421       including any package blessing as described in perlobj, as well as the
422       numeric address expressed in hex.  The ref() operator returns just the
423       type of thing the reference is pointing to, without the address.  See
424       "ref" in perlfunc for details and examples of its use.
425
426       The bless() operator may be used to associate the object a reference
427       points to with a package functioning as an object class.  See perlobj.
428
429       A typeglob may be dereferenced the same way a reference can, because
430       the dereference syntax always indicates the type of reference desired.
431       So "${*foo}" and "${\$foo}" both indicate the same scalar variable.
432
433       Here's a trick for interpolating a subroutine call into a string:
434
435           print "My sub returned @{[mysub(1,2,3)]} that time.\n";
436
437       The way it works is that when the "@{...}" is seen in the double-quoted
438       string, it's evaluated as a block.  The block creates a reference to an
439       anonymous array containing the results of the call to "mysub(1,2,3)".
440       So the whole block returns a reference to an array, which is then
441       dereferenced by "@{...}" and stuck into the double-quoted string. This
442       chicanery is also useful for arbitrary expressions:
443
444           print "That yields @{[$n + 5]} widgets\n";
445
446       Similarly, an expression that returns a reference to a scalar can be
447       dereferenced via "${...}". Thus, the above expression may be written
448       as:
449
450           print "That yields ${\($n + 5)} widgets\n";
451
452   Circular References
453       It is possible to create a "circular reference" in Perl, which can lead
454       to memory leaks. A circular reference occurs when two references
455       contain a reference to each other, like this:
456
457           my $foo = {};
458           my $bar = { foo => $foo };
459           $foo->{bar} = $bar;
460
461       You can also create a circular reference with a single variable:
462
463           my $foo;
464           $foo = \$foo;
465
466       In this case, the reference count for the variables will never reach 0,
467       and the references will never be garbage-collected. This can lead to
468       memory leaks.
469
470       Because objects in Perl are implemented as references, it's possible to
471       have circular references with objects as well. Imagine a TreeNode class
472       where each node references its parent and child nodes. Any node with a
473       parent will be part of a circular reference.
474
475       You can break circular references by creating a "weak reference". A
476       weak reference does not increment the reference count for a variable,
477       which means that the object can go out of scope and be destroyed. You
478       can weaken a reference with the "weaken" function exported by the
479       Scalar::Util module, or available as "builtin::weaken" directly in Perl
480       version 5.35.7 or later.
481
482       Here's how we can make the first example safer:
483
484           use Scalar::Util 'weaken';
485
486           my $foo = {};
487           my $bar = { foo => $foo };
488           $foo->{bar} = $bar;
489
490           weaken $foo->{bar};
491
492       The reference from $foo to $bar has been weakened. When the $bar
493       variable goes out of scope, it will be garbage-collected. The next time
494       you look at the value of the "$foo->{bar}" key, it will be "undef".
495
496       This action at a distance can be confusing, so you should be careful
497       with your use of weaken. You should weaken the reference in the
498       variable that will go out of scope first. That way, the longer-lived
499       variable will contain the expected reference until it goes out of
500       scope.
501
502   Symbolic references
503       We said that references spring into existence as necessary if they are
504       undefined, but we didn't say what happens if a value used as a
505       reference is already defined, but isn't a hard reference.  If you use
506       it as a reference, it'll be treated as a symbolic reference.  That is,
507       the value of the scalar is taken to be the name of a variable, rather
508       than a direct link to a (possibly) anonymous value.
509
510       People frequently expect it to work like this.  So it does.
511
512           $name = "foo";
513           $$name = 1;                 # Sets $foo
514           ${$name} = 2;               # Sets $foo
515           ${$name x 2} = 3;           # Sets $foofoo
516           $name->[0] = 4;             # Sets $foo[0]
517           @$name = ();                # Clears @foo
518           &$name();                   # Calls &foo()
519           $pack = "THAT";
520           ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
521
522       This is powerful, and slightly dangerous, in that it's possible to
523       intend (with the utmost sincerity) to use a hard reference, and
524       accidentally use a symbolic reference instead.  To protect against
525       that, you can say
526
527           use strict 'refs';
528
529       and then only hard references will be allowed for the rest of the
530       enclosing block.  An inner block may countermand that with
531
532           no strict 'refs';
533
534       Only package variables (globals, even if localized) are visible to
535       symbolic references.  Lexical variables (declared with my()) aren't in
536       a symbol table, and thus are invisible to this mechanism.  For example:
537
538           local $value = 10;
539           $ref = "value";
540           {
541               my $value = 20;
542               print $$ref;
543           }
544
545       This will still print 10, not 20.  Remember that local() affects
546       package variables, which are all "global" to the package.
547
548   Not-so-symbolic references
549       Brackets around a symbolic reference can simply serve to isolate an
550       identifier or variable name from the rest of an expression, just as
551       they always have within a string.  For example,
552
553           $push = "pop on ";
554           print "${push}over";
555
556       has always meant to print "pop on over", even though push is a reserved
557       word.  This is generalized to work the same without the enclosing
558       double quotes, so that
559
560           print ${push} . "over";
561
562       and even
563
564           print ${ push } . "over";
565
566       will have the same effect.  This construct is not considered to be a
567       symbolic reference when you're using strict refs:
568
569           use strict 'refs';
570           ${ bareword };      # Okay, means $bareword.
571           ${ "bareword" };    # Error, symbolic reference.
572
573       Similarly, because of all the subscripting that is done using single
574       words, the same rule applies to any bareword that is used for
575       subscripting a hash.  So now, instead of writing
576
577           $hash{ "aaa" }{ "bbb" }{ "ccc" }
578
579       you can write just
580
581           $hash{ aaa }{ bbb }{ ccc }
582
583       and not worry about whether the subscripts are reserved words.  In the
584       rare event that you do wish to do something like
585
586           $hash{ shift }
587
588       you can force interpretation as a reserved word by adding anything that
589       makes it more than a bareword:
590
591           $hash{ shift() }
592           $hash{ +shift }
593           $hash{ shift @_ }
594
595       The "use warnings" pragma or the -w switch will warn you if it
596       interprets a reserved word as a string.  But it will no longer warn you
597       about using lowercase words, because the string is effectively quoted.
598
599   Pseudo-hashes: Using an array as a hash
600       Pseudo-hashes have been removed from Perl.  The 'fields' pragma remains
601       available.
602
603   Function Templates
604       As explained above, an anonymous function with access to the lexical
605       variables visible when that function was compiled, creates a closure.
606       It retains access to those variables even though it doesn't get run
607       until later, such as in a signal handler or a Tk callback.
608
609       Using a closure as a function template allows us to generate many
610       functions that act similarly.  Suppose you wanted functions named after
611       the colors that generated HTML font changes for the various colors:
612
613           print "Be ", red("careful"), "with that ", green("light");
614
615       The red() and green() functions would be similar.  To create these,
616       we'll assign a closure to a typeglob of the name of the function we're
617       trying to build.
618
619           @colors = qw(red blue green yellow orange purple violet);
620           for my $name (@colors) {
621               no strict 'refs';       # allow symbol table manipulation
622               *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
623           }
624
625       Now all those different functions appear to exist independently.  You
626       can call red(), RED(), blue(), BLUE(), green(), etc.  This technique
627       saves on both compile time and memory use, and is less error-prone as
628       well, since syntax checks happen at compile time.  It's critical that
629       any variables in the anonymous subroutine be lexicals in order to
630       create a proper closure.  That's the reasons for the "my" on the loop
631       iteration variable.
632
633       This is one of the only places where giving a prototype to a closure
634       makes much sense.  If you wanted to impose scalar context on the
635       arguments of these functions (probably not a wise idea for this
636       particular example), you could have written it this way instead:
637
638           *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
639
640       However, since prototype checking happens at compile time, the
641       assignment above happens too late to be of much use.  You could address
642       this by putting the whole loop of assignments within a BEGIN block,
643       forcing it to occur during compilation.
644
645       Access to lexicals that change over time--like those in the "for" loop
646       above, basically aliases to elements from the surrounding lexical
647       scopes-- only works with anonymous subs, not with named subroutines.
648       Generally said, named subroutines do not nest properly and should only
649       be declared in the main package scope.
650
651       This is because named subroutines are created at compile time so their
652       lexical variables get assigned to the parent lexicals from the first
653       execution of the parent block. If a parent scope is entered a second
654       time, its lexicals are created again, while the nested subs still
655       reference the old ones.
656
657       Anonymous subroutines get to capture each time you execute the "sub"
658       operator, as they are created on the fly. If you are accustomed to
659       using nested subroutines in other programming languages with their own
660       private variables, you'll have to work at it a bit in Perl.  The
661       intuitive coding of this type of thing incurs mysterious warnings about
662       "will not stay shared" due to the reasons explained above.  For
663       example, this won't work:
664
665           sub outer {
666               my $x = $_[0] + 35;
667               sub inner { return $x * 19 }   # WRONG
668               return $x + inner();
669           }
670
671       A work-around is the following:
672
673           sub outer {
674               my $x = $_[0] + 35;
675               local *inner = sub { return $x * 19 };
676               return $x + inner();
677           }
678
679       Now inner() can only be called from within outer(), because of the
680       temporary assignments of the anonymous subroutine. But when it does, it
681       has normal access to the lexical variable $x from the scope of outer()
682       at the time outer is invoked.
683
684       This has the interesting effect of creating a function local to another
685       function, something not normally supported in Perl.
686
687   Postfix Dereference Syntax
688       Beginning in v5.20.0, a postfix syntax for using references is
689       available.  It behaves as described in "Using References", but instead
690       of a prefixed sigil, a postfixed sigil-and-star is used.
691
692       For example:
693
694           $r = \@a;
695           @b = $r->@*; # equivalent to @$r or @{ $r }
696
697           $r = [ 1, [ 2, 3 ], 4 ];
698           $r->[1]->@*;  # equivalent to @{ $r->[1] }
699
700       In Perl 5.20 and 5.22, this syntax must be enabled with use feature
701       'postderef'. As of Perl 5.24, no feature declarations are required to
702       make it available.
703
704       Postfix dereference should work in all circumstances where block
705       (circumfix) dereference worked, and should be entirely equivalent.
706       This syntax allows dereferencing to be written and read entirely left-
707       to-right.  The following equivalencies are defined:
708
709         $sref->$*;  # same as  ${ $sref }
710         $aref->@*;  # same as  @{ $aref }
711         $aref->$#*; # same as $#{ $aref }
712         $href->%*;  # same as  %{ $href }
713         $cref->&*;  # same as  &{ $cref }
714         $gref->**;  # same as  *{ $gref }
715
716       Note especially that "$cref->&*" is not equivalent to $cref->(), and
717       can serve different purposes.
718
719       Glob elements can be extracted through the postfix dereferencing
720       feature:
721
722         $gref->*{SCALAR}; # same as *{ $gref }{SCALAR}
723
724       Postfix array and scalar dereferencing can be used in interpolating
725       strings (double quotes or the "qq" operator), but only if the
726       "postderef_qq" feature is enabled. Interpolation of postfix array
727       highest index access ("->$#*") is also supported when the
728       "postderef_qq" feature is enabled.
729
730   Postfix Reference Slicing
731       Value slices of arrays and hashes may also be taken with postfix
732       dereferencing notation, with the following equivalencies:
733
734         $aref->@[ ... ];  # same as @$aref[ ... ]
735         $href->@{ ... };  # same as @$href{ ... }
736
737       Postfix key/value pair slicing, added in 5.20.0 and documented in the
738       Key/Value Hash Slices section of perldata, also behaves as expected:
739
740         $aref->%[ ... ];  # same as %$aref[ ... ]
741         $href->%{ ... };  # same as %$href{ ... }
742
743       As with postfix array, postfix value slice dereferencing can be used in
744       interpolating strings (double quotes or the "qq" operator), but only if
745       the "postderef_qq" feature is enabled.
746
747   Assigning to References
748       Beginning in v5.22.0, the referencing operator can be assigned to.  It
749       performs an aliasing operation, so that the variable name referenced on
750       the left-hand side becomes an alias for the thing referenced on the
751       right-hand side:
752
753           \$a = \$b; # $a and $b now point to the same scalar
754           \&foo = \&bar; # foo() now means bar()
755
756       This syntax must be enabled with "use feature 'refaliasing'".  It is
757       experimental, and will warn by default unless no warnings
758       'experimental::refaliasing' is in effect.
759
760       These forms may be assigned to, and cause the right-hand side to be
761       evaluated in scalar context:
762
763           \$scalar
764           \@array
765           \%hash
766           \&sub
767           \my $scalar
768           \my @array
769           \my %hash
770           \state $scalar # or @array, etc.
771           \our $scalar   # etc.
772           \local $scalar # etc.
773           \local our $scalar # etc.
774           \$some_array[$index]
775           \$some_hash{$key}
776           \local $some_array[$index]
777           \local $some_hash{$key}
778           condition ? \$this : \$that[0] # etc.
779
780       Slicing operations and parentheses cause the right-hand side to be
781       evaluated in list context:
782
783           \@array[5..7]
784           (\@array[5..7])
785           \(@array[5..7])
786           \@hash{'foo','bar'}
787           (\@hash{'foo','bar'})
788           \(@hash{'foo','bar'})
789           (\$scalar)
790           \($scalar)
791           \(my $scalar)
792           \my($scalar)
793           (\@array)
794           (\%hash)
795           (\&sub)
796           \(&sub)
797           \($foo, @bar, %baz)
798           (\$foo, \@bar, \%baz)
799
800       Each element on the right-hand side must be a reference to a datum of
801       the right type.  Parentheses immediately surrounding an array (and
802       possibly also "my"/"state"/"our"/"local") will make each element of the
803       array an alias to the corresponding scalar referenced on the right-hand
804       side:
805
806           \(@a) = \(@b); # @a and @b now have the same elements
807           \my(@a) = \(@b); # likewise
808           \(my @a) = \(@b); # likewise
809           push @a, 3; # but now @a has an extra element that @b lacks
810           \(@a) = (\$a, \$b, \$c); # @a now contains $a, $b, and $c
811
812       Combining that form with "local" and putting parentheses immediately
813       around a hash are forbidden (because it is not clear what they should
814       do):
815
816           \local(@array) = foo(); # WRONG
817           \(%hash)       = bar(); # WRONG
818
819       Assignment to references and non-references may be combined in lists
820       and conditional ternary expressions, as long as the values on the
821       right-hand side are the right type for each element on the left, though
822       this may make for obfuscated code:
823
824           (my $tom, \my $dick, \my @harry) = (\1, \2, [1..3]);
825           # $tom is now \1
826           # $dick is now 2 (read-only)
827           # @harry is (1,2,3)
828
829           my $type = ref $thingy;
830           ($type ? $type eq 'ARRAY' ? \@foo : \$bar : $baz) = $thingy;
831
832       The "foreach" loop can also take a reference constructor for its loop
833       variable, though the syntax is limited to one of the following, with an
834       optional "my", "state", or "our" after the backslash:
835
836           \$s
837           \@a
838           \%h
839           \&c
840
841       No parentheses are permitted.  This feature is particularly useful for
842       arrays-of-arrays, or arrays-of-hashes:
843
844           foreach \my @a (@array_of_arrays) {
845               frobnicate($a[0], $a[-1]);
846           }
847
848           foreach \my %h (@array_of_hashes) {
849               $h{gelastic}++ if $h{type} eq 'funny';
850           }
851
852       CAVEAT: Aliasing does not work correctly with closures.  If you try to
853       alias lexical variables from an inner subroutine or "eval", the
854       aliasing will only be visible within that inner sub, and will not
855       affect the outer subroutine where the variables are declared.  This
856       bizarre behavior is subject to change.
857
858   Declaring a Reference to a Variable
859       Beginning in v5.26.0, the referencing operator can come after "my",
860       "state", "our", or "local".  This syntax must be enabled with "use
861       feature 'declared_refs'".  It is experimental, and will warn by default
862       unless "no warnings 'experimental::refaliasing'" is in effect.
863
864       This feature makes these:
865
866           my \$x;
867           our \$y;
868
869       equivalent to:
870
871           \my $x;
872           \our $x;
873
874       It is intended mainly for use in assignments to references (see
875       "Assigning to References", above).  It also allows the backslash to be
876       used on just some items in a list of declared variables:
877
878           my ($foo, \@bar, \%baz); # equivalent to:  my $foo, \my(@bar, %baz);
879

WARNING: Don't use references as hash keys

881       You may not (usefully) use a reference as the key to a hash.  It will
882       be converted into a string:
883
884           $x{ \$a } = $a;
885
886       If you try to dereference the key, it won't do a hard dereference, and
887       you won't accomplish what you're attempting.  You might want to do
888       something more like
889
890           $r = \@a;
891           $x{ $r } = $r;
892
893       And then at least you can use the values(), which will be real refs,
894       instead of the keys(), which won't.
895
896       The standard Tie::RefHash module provides a convenient workaround to
897       this.
898

SEE ALSO

900       Besides the obvious documents, source code can be instructive.  Some
901       pathological examples of the use of references can be found in the
902       t/op/ref.t regression test in the Perl source directory.
903
904       See also perldsc and perllol for how to use references to create
905       complex data structures, and perlootut and perlobj for how to use them
906       to create objects.
907
908
909
910perl v5.38.2                      2023-11-30                        PERLREF(1)
Impressum