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