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 vari‐
18       ables, but also lets you have "hard" references to any piece of data or
19       code.  Any scalar may hold a hard reference.  Because arrays and hashes
20       contain scalars, you can now easily build arrays of arrays, arrays of
21       hashes, hashes of arrays, arrays of hashes of functions, and so on.
22
23       Hard references are smart--they keep track of reference counts for you,
24       automatically freeing the thing referred to when its reference count
25       goes to zero.  (Reference counts for values in self-referential or
26       cyclic data structures may not go to zero without a little help; see
27       "Two-Phased Garbage Collection" in perlobj for a detailed explanation.)
28       If that thing happens to be an object, the object is destructed.  See
29       perlobj for more about objects.  (In a sense, everything in Perl is an
30       object, but we usually reserve the word for references to objects that
31       have been officially "blessed" into a class package.)
32
33       Symbolic references are names of variables or other objects, just as a
34       symbolic link in a Unix filesystem contains merely the name of a file.
35       The *glob notation is something of a symbolic reference.  (Symbolic
36       references are sometimes called "soft references", but please don't
37       call them that; references are confusing enough without useless syn‐
38       onyms.)
39
40       In contrast, hard references are more like hard links in a Unix file
41       system: They are used to access an underlying object without concern
42       for what its (other) name is.  When the word "reference" is used with‐
43       out an adjective, as in the following paragraph, it is usually talking
44       about a hard reference.
45
46       References are easy to use in Perl.  There is just one overriding prin‐
47       ciple: Perl does no implicit referencing or dereferencing.  When a
48       scalar is holding a reference, it always behaves as a simple scalar.
49       It doesn't magically start being an array or hash or subroutine; you
50       have to tell it explicitly to do so, by dereferencing it.
51
52       Making References
53
54       References can be created in several ways.
55
56       1.  By using the backslash operator on a variable, subroutine, or
57           value.  (This works much like the & (address-of) operator in C.)
58           This typically creates another reference to a variable, because
59           there's already a reference to the variable in the symbol table.
60           But the symbol table reference might go away, and you'll still have
61           the reference that the backslash returned.  Here are some examples:
62
63               $scalarref = \$foo;
64               $arrayref  = \@ARGV;
65               $hashref   = \%ENV;
66               $coderef   = \&handler;
67               $globref   = \*foo;
68
69           It isn't possible to create a true reference to an IO handle (file‐
70           handle or dirhandle) using the backslash operator.  The most you
71           can get is a reference to a typeglob, which is actually a complete
72           symbol table entry.  But see the explanation of the *foo{THING}
73           syntax below.  However, you can still use type globs and globrefs
74           as though they were IO handles.
75
76       2.  A reference to an anonymous array can be created using square
77           brackets:
78
79               $arrayref = [1, 2, ['a', 'b', 'c']];
80
81           Here we've created a reference to an anonymous array of three ele‐
82           ments whose final element is itself a reference to another anony‐
83           mous array of three elements.  (The multidimensional syntax
84           described later can be used to access this.  For example, after the
85           above, "$arrayref->[2][1]" would have the value "b".)
86
87           Taking a reference to an enumerated list is not the same as using
88           square brackets--instead it's the same as creating a list of refer‐
89           ences!
90
91               @list = (\$a, \@b, \%c);
92               @list = \($a, @b, %c);      # same thing!
93
94           As a special case, "\(@foo)" returns a list of references to the
95           contents of @foo, not a reference to @foo itself.  Likewise for
96           %foo, except that the key references are to copies (since the keys
97           are just strings rather than full-fledged scalars).
98
99       3.  A reference to an anonymous hash can be created using curly brack‐
100           ets:
101
102               $hashref = {
103                   'Adam'  => 'Eve',
104                   'Clyde' => 'Bonnie',
105               };
106
107           Anonymous hash and array composers like these can be intermixed
108           freely to produce as complicated a structure as you want.  The mul‐
109           tidimensional syntax described below works for these too.  The val‐
110           ues above are literals, but variables and expressions would work
111           just as well, because assignment operators in Perl (even within
112           local() or my()) are executable statements, not compile-time decla‐
113           rations.
114
115           Because curly brackets (braces) are used for several other things
116           including BLOCKs, you may occasionally have to disambiguate braces
117           at the beginning of a statement by putting a "+" or a "return" in
118           front so that Perl realizes the opening brace isn't starting a
119           BLOCK.  The economy and mnemonic value of using curlies is deemed
120           worth this occasional extra hassle.
121
122           For example, if you wanted a function to make a new hash and return
123           a reference to it, you have these options:
124
125               sub hashem {        { @_ } }   # silently wrong
126               sub hashem {       +{ @_ } }   # ok
127               sub hashem { return { @_ } }   # ok
128
129           On the other hand, if you want the other meaning, you can do this:
130
131               sub showem {        { @_ } }   # ambiguous (currently ok, but may change)
132               sub showem {       {; @_ } }   # ok
133               sub showem { { return @_ } }   # ok
134
135           The leading "+{" and "{;" always serve to disambiguate the expres‐
136           sion to mean either the HASH reference, or the BLOCK.
137
138       4.  A reference to an anonymous subroutine can be created by using
139           "sub" without a subname:
140
141               $coderef = sub { print "Boink!\n" };
142
143           Note the semicolon.  Except for the code inside not being immedi‐
144           ately executed, a "sub {}" is not so much a declaration as it is an
145           operator, like "do{}" or "eval{}".  (However, no matter how many
146           times you execute that particular line (unless you're in an
147           "eval("...")"), $coderef will still have a reference to the same
148           anonymous subroutine.)
149
150           Anonymous subroutines act as closures with respect to my() vari‐
151           ables, that is, variables lexically visible within the current
152           scope.  Closure is a notion out of the Lisp world that says if you
153           define an anonymous function in a particular lexical context, it
154           pretends to run in that context even when it's called outside the
155           context.
156
157           In human terms, it's a funny way of passing arguments to a subrou‐
158           tine when you define it as well as when you call it.  It's useful
159           for setting up little bits of code to run later, such as callbacks.
160           You can even do object-oriented stuff with it, though Perl already
161           provides a different mechanism to do that--see perlobj.
162
163           You might also think of closure as a way to write a subroutine tem‐
164           plate without using eval().  Here's a small example of how closures
165           work:
166
167               sub newprint {
168                   my $x = shift;
169                   return sub { my $y = shift; print "$x, $y!\n"; };
170               }
171               $h = newprint("Howdy");
172               $g = newprint("Greetings");
173
174               # Time passes...
175
176               &$h("world");
177               &$g("earthlings");
178
179           This prints
180
181               Howdy, world!
182               Greetings, earthlings!
183
184           Note particularly that $x continues to refer to the value passed
185           into newprint() despite "my $x" having gone out of scope by the
186           time the anonymous subroutine runs.  That's what a closure is all
187           about.
188
189           This applies only to lexical variables, by the way.  Dynamic vari‐
190           ables continue to work as they have always worked.  Closure is not
191           something that most Perl programmers need trouble themselves about
192           to begin with.
193
194       5.  References are often returned by special subroutines called con‐
195           structors.  Perl objects are just references to a special type of
196           object that happens to know which package it's associated with.
197           Constructors are just special subroutines that know how to create
198           that association.  They do so by starting with an ordinary refer‐
199           ence, and it remains an ordinary reference even while it's also
200           being an object.  Constructors are often named new() and called
201           indirectly:
202
203               $objref = new Doggie (Tail => 'short', Ears => 'long');
204
205           But don't have to be:
206
207               $objref   = Doggie->new(Tail => 'short', Ears => 'long');
208
209               use Term::Cap;
210               $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
211
212               use Tk;
213               $main    = MainWindow->new();
214               $menubar = $main->Frame(-relief              => "raised",
215                                       -borderwidth         => 2)
216
217       6.  References of the appropriate type can spring into existence if you
218           dereference them in a context that assumes they exist.  Because we
219           haven't talked about dereferencing yet, we can't show you any exam‐
220           ples yet.
221
222       7.  A reference can be created by using a special syntax, lovingly
223           known as the *foo{THING} syntax.  *foo{THING} returns a reference
224           to the THING slot in *foo (which is the symbol table entry which
225           holds everything known as foo).
226
227               $scalarref = *foo{SCALAR};
228               $arrayref  = *ARGV{ARRAY};
229               $hashref   = *ENV{HASH};
230               $coderef   = *handler{CODE};
231               $ioref     = *STDIN{IO};
232               $globref   = *foo{GLOB};
233               $formatref = *foo{FORMAT};
234
235           All of these are self-explanatory except for *foo{IO}.  It returns
236           the IO handle, used for file handles ("open" in perlfunc), sockets
237           ("socket" in perlfunc and "socketpair" in perlfunc), and directory
238           handles ("opendir" in perlfunc).  For compatibility with previous
239           versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO},
240           though it is deprecated as of 5.8.0.  If deprecation warnings are
241           in effect, it will warn of its use.
242
243           *foo{THING} returns undef if that particular THING hasn't been used
244           yet, except in the case of scalars.  *foo{SCALAR} returns a refer‐
245           ence to an anonymous scalar if $foo hasn't been used yet.  This
246           might change in a future release.
247
248           *foo{IO} is an alternative to the *HANDLE mechanism given in "Type‐
249           globs and Filehandles" in perldata for passing filehandles into or
250           out of subroutines, or storing into larger data structures.  Its
251           disadvantage is that it won't create a new filehandle for you.  Its
252           advantage is that you have less risk of clobbering more than you
253           want to with a typeglob assignment.  (It still conflates file and
254           directory handles, though.)  However, if you assign the incoming
255           value to a scalar instead of a typeglob as we do in the examples
256           below, there's no risk of that happening.
257
258               splutter(*STDOUT);          # pass the whole glob
259               splutter(*STDOUT{IO});      # pass both file and dir handles
260
261               sub splutter {
262                   my $fh = shift;
263                   print $fh "her um well a hmmm\n";
264               }
265
266               $rec = get_rec(*STDIN);     # pass the whole glob
267               $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
268
269               sub get_rec {
270                   my $fh = shift;
271                   return scalar <$fh>;
272               }
273
274       Using References
275
276       That's it for creating references.  By now you're probably dying to
277       know how to use references to get back to your long-lost data.  There
278       are several basic methods.
279
280       1.  Anywhere you'd put an identifier (or chain of identifiers) as part
281           of a variable or subroutine name, you can replace the identifier
282           with a simple scalar variable containing a reference of the correct
283           type:
284
285               $bar = $$scalarref;
286               push(@$arrayref, $filename);
287               $$arrayref[0] = "January";
288               $$hashref{"KEY"} = "VALUE";
289               &$coderef(1,2,3);
290               print $globref "output\n";
291
292           It's important to understand that we are specifically not derefer‐
293           encing $arrayref[0] or $hashref{"KEY"} there.  The dereference of
294           the scalar variable happens before it does any key lookups.  Any‐
295           thing more complicated than a simple scalar variable must use meth‐
296           ods 2 or 3 below.  However, a "simple scalar" includes an identi‐
297           fier that itself uses method 1 recursively.  Therefore, the follow‐
298           ing prints "howdy".
299
300               $refrefref = \\\"howdy";
301               print $$$$refrefref;
302
303       2.  Anywhere you'd put an identifier (or chain of identifiers) as part
304           of a variable or subroutine name, you can replace the identifier
305           with a BLOCK returning a reference of the correct type.  In other
306           words, the previous examples could be written like this:
307
308               $bar = ${$scalarref};
309               push(@{$arrayref}, $filename);
310               ${$arrayref}[0] = "January";
311               ${$hashref}{"KEY"} = "VALUE";
312               &{$coderef}(1,2,3);
313               $globref->print("output\n");  # iff IO::Handle is loaded
314
315           Admittedly, it's a little silly to use the curlies in this case,
316           but the BLOCK can contain any arbitrary expression, in particular,
317           subscripted expressions:
318
319               &{ $dispatch{$index} }(1,2,3);      # call correct routine
320
321           Because of being able to omit the curlies for the simple case of
322           $$x, people often make the mistake of viewing the dereferencing
323           symbols as proper operators, and wonder about their precedence.  If
324           they were, though, you could use parentheses instead of braces.
325           That's not the case.  Consider the difference below; case 0 is a
326           short-hand version of case 1, not case 2:
327
328               $$hashref{"KEY"}   = "VALUE";       # CASE 0
329               ${$hashref}{"KEY"} = "VALUE";       # CASE 1
330               ${$hashref{"KEY"}} = "VALUE";       # CASE 2
331               ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
332
333           Case 2 is also deceptive in that you're accessing a variable called
334           %hashref, not dereferencing through $hashref to the hash it's pre‐
335           sumably referencing.  That would be case 3.
336
337       3.  Subroutine calls and lookups of individual array elements arise
338           often enough that it gets cumbersome to use method 2.  As a form of
339           syntactic sugar, the examples for method 2 may be written:
340
341               $arrayref->[0] = "January";   # Array element
342               $hashref->{"KEY"} = "VALUE";  # Hash element
343               $coderef->(1,2,3);            # Subroutine call
344
345           The left side of the arrow can be any expression returning a refer‐
346           ence, including a previous dereference.  Note that $array[$x] is
347           not the same thing as "$array->[$x]" here:
348
349               $array[$x]->{"foo"}->[0] = "January";
350
351           This is one of the cases we mentioned earlier in which references
352           could spring into existence when in an lvalue context.  Before this
353           statement, $array[$x] may have been undefined.  If so, it's auto‐
354           matically defined with a hash reference so that we can look up
355           "{"foo"}" in it.  Likewise "$array[$x]->{"foo"}" will automatically
356           get defined with an array reference so that we can look up "[0]" in
357           it.  This process is called autovivification.
358
359           One more thing here.  The arrow is optional between brackets sub‐
360           scripts, so you can shrink the above down to
361
362               $array[$x]{"foo"}[0] = "January";
363
364           Which, in the degenerate case of using only ordinary arrays, gives
365           you multidimensional arrays just like C's:
366
367               $score[$x][$y][$z] += 42;
368
369           Well, okay, not entirely like C's arrays, actually.  C doesn't know
370           how to grow its arrays on demand.  Perl does.
371
372       4.  If a reference happens to be a reference to an object, then there
373           are probably methods to access the things referred to, and you
374           should probably stick to those methods unless you're in the class
375           package that defines the object's methods.  In other words, be
376           nice, and don't violate the object's encapsulation without a very
377           good reason.  Perl does not enforce encapsulation.  We are not
378           totalitarians here.  We do expect some basic civility though.
379
380       Using a string or number as a reference produces a symbolic reference,
381       as explained above.  Using a reference as a number produces an integer
382       representing its storage location in memory.  The only useful thing to
383       be done with this is to compare two references numerically to see
384       whether they refer to the same location.
385
386           if ($ref1 == $ref2) {  # cheap numeric compare of references
387               print "refs 1 and 2 refer to the same thing\n";
388           }
389
390       Using a reference as a string produces both its referent's type,
391       including any package blessing as described in perlobj, as well as the
392       numeric address expressed in hex.  The ref() operator returns just the
393       type of thing the reference is pointing to, without the address.  See
394       "ref" in perlfunc for details and examples of its use.
395
396       The bless() operator may be used to associate the object a reference
397       points to with a package functioning as an object class.  See perlobj.
398
399       A typeglob may be dereferenced the same way a reference can, because
400       the dereference syntax always indicates the type of reference desired.
401       So "${*foo}" and "${\$foo}" both indicate the same scalar variable.
402
403       Here's a trick for interpolating a subroutine call into a string:
404
405           print "My sub returned @{[mysub(1,2,3)]} that time.\n";
406
407       The way it works is that when the "@{...}" is seen in the double-quoted
408       string, it's evaluated as a block.  The block creates a reference to an
409       anonymous array containing the results of the call to "mysub(1,2,3)".
410       So the whole block returns a reference to an array, which is then
411       dereferenced by "@{...}" and stuck into the double-quoted string. This
412       chicanery is also useful for arbitrary expressions:
413
414           print "That yields @{[$n + 5]} widgets\n";
415
416       Symbolic references
417
418       We said that references spring into existence as necessary if they are
419       undefined, but we didn't say what happens if a value used as a refer‐
420       ence is already defined, but isn't a hard reference.  If you use it as
421       a reference, it'll be treated as a symbolic reference.  That is, the
422       value of the scalar is taken to be the name of a variable, rather than
423       a direct link to a (possibly) anonymous value.
424
425       People frequently expect it to work like this.  So it does.
426
427           $name = "foo";
428           $$name = 1;                 # Sets $foo
429           ${$name} = 2;               # Sets $foo
430           ${$name x 2} = 3;           # Sets $foofoo
431           $name->[0] = 4;             # Sets $foo[0]
432           @$name = ();                # Clears @foo
433           &$name();                   # Calls &foo() (as in Perl 4)
434           $pack = "THAT";
435           ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
436
437       This is powerful, and slightly dangerous, in that it's possible to
438       intend (with the utmost sincerity) to use a hard reference, and acci‐
439       dentally use a symbolic reference instead.  To protect against that,
440       you can say
441
442           use strict 'refs';
443
444       and then only hard references will be allowed for the rest of the
445       enclosing block.  An inner block may countermand that with
446
447           no strict 'refs';
448
449       Only package variables (globals, even if localized) are visible to sym‐
450       bolic references.  Lexical variables (declared with my()) aren't in a
451       symbol table, and thus are invisible to this mechanism.  For example:
452
453           local $value = 10;
454           $ref = "value";
455           {
456               my $value = 20;
457               print $$ref;
458           }
459
460       This will still print 10, not 20.  Remember that local() affects pack‐
461       age variables, which are all "global" to the package.
462
463       Not-so-symbolic references
464
465       A new feature contributing to readability in perl version 5.001 is that
466       the brackets around a symbolic reference behave more like quotes, just
467       as they always have within a string.  That is,
468
469           $push = "pop on ";
470           print "${push}over";
471
472       has always meant to print "pop on over", even though push is a reserved
473       word.  This has been generalized to work the same outside of quotes, so
474       that
475
476           print ${push} . "over";
477
478       and even
479
480           print ${ push } . "over";
481
482       will have the same effect.  (This would have been a syntax error in
483       Perl 5.000, though Perl 4 allowed it in the spaceless form.)  This con‐
484       struct is not considered to be a symbolic reference when you're using
485       strict refs:
486
487           use strict 'refs';
488           ${ bareword };      # Okay, means $bareword.
489           ${ "bareword" };    # Error, symbolic reference.
490
491       Similarly, because of all the subscripting that is done using single
492       words, we've applied the same rule to any bareword that is used for
493       subscripting a hash.  So now, instead of writing
494
495           $array{ "aaa" }{ "bbb" }{ "ccc" }
496
497       you can write just
498
499           $array{ aaa }{ bbb }{ ccc }
500
501       and not worry about whether the subscripts are reserved words.  In the
502       rare event that you do wish to do something like
503
504           $array{ shift }
505
506       you can force interpretation as a reserved word by adding anything that
507       makes it more than a bareword:
508
509           $array{ shift() }
510           $array{ +shift }
511           $array{ shift @_ }
512
513       The "use warnings" pragma or the -w switch will warn you if it inter‐
514       prets a reserved word as a string.  But it will no longer warn you
515       about using lowercase words, because the string is effectively quoted.
516
517       Pseudo-hashes: Using an array as a hash
518
519       WARNING:  This section describes an experimental feature.  Details may
520       change without notice in future versions.
521
522       NOTE: The current user-visible implementation of pseudo-hashes (the
523       weird use of the first array element) is deprecated starting from Perl
524       5.8.0 and will be removed in Perl 5.10.0, and the feature will be
525       implemented differently.  Not only is the current interface rather
526       ugly, but the current implementation slows down normal array and hash
527       use quite noticeably.  The 'fields' pragma interface will remain avail‐
528       able.
529
530       Beginning with release 5.005 of Perl, you may use an array reference in
531       some contexts that would normally require a hash reference.  This
532       allows you to access array elements using symbolic names, as if they
533       were fields in a structure.
534
535       For this to work, the array must contain extra information.  The first
536       element of the array has to be a hash reference that maps field names
537       to array indices.  Here is an example:
538
539           $struct = [{foo => 1, bar => 2}, "FOO", "BAR"];
540
541           $struct->{foo};  # same as $struct->[1], i.e. "FOO"
542           $struct->{bar};  # same as $struct->[2], i.e. "BAR"
543
544           keys %$struct;   # will return ("foo", "bar") in some order
545           values %$struct; # will return ("FOO", "BAR") in same some order
546
547           while (my($k,$v) = each %$struct) {
548              print "$k => $v\n";
549           }
550
551       Perl will raise an exception if you try to access nonexistent fields.
552       To avoid inconsistencies, always use the fields::phash() function pro‐
553       vided by the "fields" pragma.
554
555           use fields;
556           $pseudohash = fields::phash(foo => "FOO", bar => "BAR");
557
558       For better performance, Perl can also do the translation from field
559       names to array indices at compile time for typed object references.
560       See fields.
561
562       There are two ways to check for the existence of a key in a
563       pseudo-hash.  The first is to use exists().  This checks to see if the
564       given field has ever been set.  It acts this way to match the behavior
565       of a regular hash.  For instance:
566
567           use fields;
568           $phash = fields::phash([qw(foo bar pants)], ['FOO']);
569           $phash->{pants} = undef;
570
571           print exists $phash->{foo};    # true, 'foo' was set in the declaration
572           print exists $phash->{bar};    # false, 'bar' has not been used.
573           print exists $phash->{pants};  # true, your 'pants' have been touched
574
575       The second is to use exists() on the hash reference sitting in the
576       first array element.  This checks to see if the given key is a valid
577       field in the pseudo-hash.
578
579           print exists $phash->[0]{bar};      # true, 'bar' is a valid field
580           print exists $phash->[0]{shoes};# false, 'shoes' can't be used
581
582       delete() on a pseudo-hash element only deletes the value corresponding
583       to the key, not the key itself.  To delete the key, you'll have to
584       explicitly delete it from the first hash element.
585
586           print delete $phash->{foo};     # prints $phash->[1], "FOO"
587           print exists $phash->{foo};     # false
588           print exists $phash->[0]{foo};  # true, key still exists
589           print delete $phash->[0]{foo};  # now key is gone
590           print $phash->{foo};            # runtime exception
591
592       Function Templates
593
594       As explained above, an anonymous function with access to the lexical
595       variables visible when that function was compiled, creates a closure.
596       It retains access to those variables even though it doesn't get run
597       until later, such as in a signal handler or a Tk callback.
598
599       Using a closure as a function template allows us to generate many func‐
600       tions that act similarly.  Suppose you wanted functions named after the
601       colors that generated HTML font changes for the various colors:
602
603           print "Be ", red("careful"), "with that ", green("light");
604
605       The red() and green() functions would be similar.  To create these,
606       we'll assign a closure to a typeglob of the name of the function we're
607       trying to build.
608
609           @colors = qw(red blue green yellow orange purple violet);
610           for my $name (@colors) {
611               no strict 'refs';       # allow symbol table manipulation
612               *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
613           }
614
615       Now all those different functions appear to exist independently.  You
616       can call red(), RED(), blue(), BLUE(), green(), etc.  This technique
617       saves on both compile time and memory use, and is less error-prone as
618       well, since syntax checks happen at compile time.  It's critical that
619       any variables in the anonymous subroutine be lexicals in order to cre‐
620       ate a proper closure.  That's the reasons for the "my" on the loop
621       iteration variable.
622
623       This is one of the only places where giving a prototype to a closure
624       makes much sense.  If you wanted to impose scalar context on the argu‐
625       ments of these functions (probably not a wise idea for this particular
626       example), you could have written it this way instead:
627
628           *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
629
630       However, since prototype checking happens at compile time, the assign‐
631       ment above happens too late to be of much use.  You could address this
632       by putting the whole loop of assignments within a BEGIN block, forcing
633       it to occur during compilation.
634
635       Access to lexicals that change over type--like those in the "for" loop
636       above--only works with closures, not general subroutines.  In the gen‐
637       eral case, then, named subroutines do not nest properly, although
638       anonymous ones do. Thus is because named subroutines are created (and
639       capture any outer lexicals) only once at compile time, whereas anony‐
640       mous subroutines get to capture each time you execute the 'sub' opera‐
641       tor.  If you are accustomed to using nested subroutines in other pro‐
642       gramming languages with their own private variables, you'll have to
643       work at it a bit in Perl.  The intuitive coding of this type of thing
644       incurs mysterious warnings about "will not stay shared".  For example,
645       this won't work:
646
647           sub outer {
648               my $x = $_[0] + 35;
649               sub inner { return $x * 19 }   # WRONG
650               return $x + inner();
651           }
652
653       A work-around is the following:
654
655           sub outer {
656               my $x = $_[0] + 35;
657               local *inner = sub { return $x * 19 };
658               return $x + inner();
659           }
660
661       Now inner() can only be called from within outer(), because of the tem‐
662       porary assignments of the closure (anonymous subroutine).  But when it
663       does, it has normal access to the lexical variable $x from the scope of
664       outer().
665
666       This has the interesting effect of creating a function local to another
667       function, something not normally supported in Perl.
668

WARNING

670       You may not (usefully) use a reference as the key to a hash.  It will
671       be converted into a string:
672
673           $x{ \$a } = $a;
674
675       If you try to dereference the key, it won't do a hard dereference, and
676       you won't accomplish what you're attempting.  You might want to do
677       something more like
678
679           $r = \@a;
680           $x{ $r } = $r;
681
682       And then at least you can use the values(), which will be real refs,
683       instead of the keys(), which won't.
684
685       The standard Tie::RefHash module provides a convenient workaround to
686       this.
687

SEE ALSO

689       Besides the obvious documents, source code can be instructive.  Some
690       pathological examples of the use of references can be found in the
691       t/op/ref.t regression test in the Perl source directory.
692
693       See also perldsc and perllol for how to use references to create com‐
694       plex data structures, and perltoot, perlobj, and perlbot for how to use
695       them to create objects.
696
697
698
699perl v5.8.8                       2006-01-07                        PERLREF(1)
Impressum