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