5.004_58 | _04: pod2*,perlpod: L<show this|man/section>
[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 that was
9 difficult to do when you wanted to refer to a variable rather than a
10 symbol table entry.  Perl not only makes it easier to use symbolic
11 references to variables, but lets you have "hard" references to any piece
12 of data.  Any scalar may hold a hard reference.  Because arrays and hashes
13 contain scalars, you can now easily build arrays of arrays, arrays of
14 hashes, 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, like in the following paragraph, it usually is 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 References can be constructed in several ways.
45
46 =over 4
47
48 =item 1.
49
50 By using the backslash operator on a variable, subroutine, or value.
51 (This works much like the & (address-of) operator in C.)  Note
52 that this typically creates I<ANOTHER> reference to a variable, because
53 there's already a reference to the variable in the symbol table.  But
54 the symbol table reference might go away, and you'll still have the
55 reference that the backslash returned.  Here are some examples:
56
57     $scalarref = \$foo;
58     $arrayref  = \@ARGV;
59     $hashref   = \%ENV;
60     $coderef   = \&handler;
61     $globref   = \*foo;
62
63 It isn't possible to create a true reference to an IO handle (filehandle or
64 dirhandle) using the backslash operator.  See the explanation of the
65 *foo{THING} syntax below.  (However, you're apt to find Perl code
66 out there using globrefs as though they were IO handles, which is
67 grandfathered into continued functioning.)
68
69 =item 2.
70
71 A reference to an anonymous array can be constructed using square
72 brackets:
73
74     $arrayref = [1, 2, ['a', 'b', 'c']];
75
76 Here we've constructed a reference to an anonymous array of three elements
77 whose final element is itself a reference to another anonymous array of three
78 elements.  (The multidimensional syntax described later can be used to
79 access this.  For example, after the above, C<$arrayref-E<gt>[2][1]> would have
80 the value "b".)
81
82 Note that taking a reference to an enumerated list is not the same
83 as using square brackets--instead it's the same as creating
84 a list of references!
85
86     @list = (\$a, \@b, \%c);
87     @list = \($a, @b, %c);      # same thing!
88
89 As a special case, C<\(@foo)> returns a list of references to the contents
90 of C<@foo>, not a reference to C<@foo> itself.  Likewise for C<%foo>.
91
92 =item 3.
93
94 A reference to an anonymous hash can be constructed using curly
95 brackets:
96
97     $hashref = {
98         'Adam'  => 'Eve',
99         'Clyde' => 'Bonnie',
100     };
101
102 Anonymous hash and array constructors can be intermixed freely to
103 produce as complicated a structure as you want.  The multidimensional
104 syntax described below works for these too.  The values above are
105 literals, but variables and expressions would work just as well, because
106 assignment operators in Perl (even within local() or my()) are executable
107 statements, not compile-time declarations.
108
109 Because curly brackets (braces) are used for several other things
110 including BLOCKs, you may occasionally have to disambiguate braces at the
111 beginning of a statement by putting a C<+> or a C<return> in front so
112 that Perl realizes the opening brace isn't starting a BLOCK.  The economy and
113 mnemonic value of using curlies is deemed worth this occasional extra
114 hassle.
115
116 For example, if you wanted a function to make a new hash and return a
117 reference to it, you have these options:
118
119     sub hashem {        { @_ } }   # silently wrong
120     sub hashem {       +{ @_ } }   # ok
121     sub hashem { return { @_ } }   # ok
122
123 =item 4.
124
125 A reference to an anonymous subroutine can be constructed by using
126 C<sub> without a subname:
127
128     $coderef = sub { print "Boink!\n" };
129
130 Note the presence of the semicolon.  Except for the fact that the code
131 inside isn't executed immediately, a C<sub {}> is not so much a
132 declaration as it is an operator, like C<do{}> or C<eval{}>.  (However, no
133 matter how many times you execute that line (unless you're in an
134 C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
135 anonymous subroutine.)
136
137 Anonymous subroutines act as closures with respect to my() variables,
138 that is, variables visible lexically within the current scope.  Closure
139 is a notion out of the Lisp world that says if you define an anonymous
140 function in a particular lexical context, it pretends to run in that
141 context even when it's called outside of the context.
142
143 In human terms, it's a funny way of passing arguments to a subroutine when
144 you define it as well as when you call it.  It's useful for setting up
145 little bits of code to run later, such as callbacks.  You can even
146 do object-oriented stuff with it, though Perl already provides a different
147 mechanism to do that--see L<perlobj>.
148
149 You can also think of closure as a way to write a subroutine template without
150 using eval.  (In fact, in version 5.000, eval was the I<only> way to get
151 closures.  You may wish to use "require 5.001" if you use closures.)
152
153 Here's a small example of how closures works:
154
155     sub newprint {
156         my $x = shift;
157         return sub { my $y = shift; print "$x, $y!\n"; };
158     }
159     $h = newprint("Howdy");
160     $g = newprint("Greetings");
161
162     # Time passes...
163
164     &$h("world");
165     &$g("earthlings");
166
167 This prints
168
169     Howdy, world!
170     Greetings, earthlings!
171
172 Note particularly that $x continues to refer to the value passed into
173 newprint() I<despite> the fact that the "my $x" has seemingly gone out of
174 scope by the time the anonymous subroutine runs.  That's what closure
175 is all about.
176
177 This applies to only lexical variables, by the way.  Dynamic variables
178 continue to work as they have always worked.  Closure is not something
179 that most Perl programmers need trouble themselves about to begin with.
180
181 =item 5.
182
183 References are often returned by special subroutines called constructors.
184 Perl objects are just references to a special kind of object that happens to know
185 which package it's associated with.  Constructors are just special
186 subroutines that know how to create that association.  They do so by
187 starting with an ordinary reference, and it remains an ordinary reference
188 even while it's also being an object.  Constructors are customarily
189 named new(), but don't have to be:
190
191     $objref = new Doggie (Tail => 'short', Ears => 'long');
192
193 =item 6.
194
195 References of the appropriate type can spring into existence if you
196 dereference them in a context that assumes they exist.  Because we haven't
197 talked about dereferencing yet, we can't show you any examples yet.
198
199 =item 7.
200
201 A reference can be created by using a special syntax, lovingly known as
202 the *foo{THING} syntax.  *foo{THING} returns a reference to the THING
203 slot in *foo (which is the symbol table entry which holds everything
204 known as foo).
205
206     $scalarref = *foo{SCALAR};
207     $arrayref  = *ARGV{ARRAY};
208     $hashref   = *ENV{HASH};
209     $coderef   = *handler{CODE};
210     $ioref     = *STDIN{IO};
211     $globref   = *foo{GLOB};
212
213 All of these are self-explanatory except for *foo{IO}.  It returns the
214 IO handle, used for file handles (L<perlfunc/open>), sockets
215 (L<perlfunc/socket> and L<perlfunc/socketpair>), and directory handles
216 (L<perlfunc/opendir>).  For compatibility with previous versions of
217 Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}.
218
219 *foo{THING} returns undef if that particular THING hasn't been used yet,
220 except in the case of scalars.  *foo{SCALAR} returns a reference to an
221 anonymous scalar if $foo hasn't been used yet.  This might change in a
222 future release.
223
224 The use of *foo{IO} is the best way to pass bareword filehandles into or
225 out of subroutines, or to store them in larger data structures.
226
227     splutter(*STDOUT{IO});
228     sub splutter {
229         my $fh = shift;
230         print $fh "her um well a hmmm\n";
231     }
232
233     $rec = get_rec(*STDIN{IO});
234     sub get_rec {
235         my $fh = shift;
236         return scalar <$fh>;
237     }
238
239 Beware, though, that you can't do this with a routine which is going to
240 open the filehandle for you, because *HANDLE{IO} will be undef if HANDLE
241 hasn't been used yet.  Use \*HANDLE for that sort of thing instead.
242
243 Using \*HANDLE (or *HANDLE) is another way to use and store non-bareword
244 filehandles (before perl version 5.002 it was the only way).  The two
245 methods are largely interchangeable, you can do
246
247     splutter(\*STDOUT);
248     $rec = get_rec(\*STDIN);
249
250 with the above subroutine definitions.
251
252 =back
253
254 That's it for creating references.  By now you're probably dying to
255 know how to use references to get back to your long-lost data.  There
256 are several basic methods.
257
258 =over 4
259
260 =item 1.
261
262 Anywhere you'd put an identifier (or chain of identifiers) as part
263 of a variable or subroutine name, you can replace the identifier with
264 a simple scalar variable containing a reference of the correct type:
265
266     $bar = $$scalarref;
267     push(@$arrayref, $filename);
268     $$arrayref[0] = "January";
269     $$hashref{"KEY"} = "VALUE";
270     &$coderef(1,2,3);
271     print $globref "output\n";
272
273 It's important to understand that we are specifically I<NOT> dereferencing
274 C<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of the
275 scalar variable happens I<BEFORE> it does any key lookups.  Anything more
276 complicated than a simple scalar variable must use methods 2 or 3 below.
277 However, a "simple scalar" includes an identifier that itself uses method
278 1 recursively.  Therefore, the following prints "howdy".
279
280     $refrefref = \\\"howdy";
281     print $$$$refrefref;
282
283 =item 2.
284
285 Anywhere you'd put an identifier (or chain of identifiers) as part of a
286 variable or subroutine name, you can replace the identifier with a
287 BLOCK returning a reference of the correct type.  In other words, the
288 previous examples could be written like this:
289
290     $bar = ${$scalarref};
291     push(@{$arrayref}, $filename);
292     ${$arrayref}[0] = "January";
293     ${$hashref}{"KEY"} = "VALUE";
294     &{$coderef}(1,2,3);
295     $globref->print("output\n");  # iff IO::Handle is loaded
296
297 Admittedly, it's a little silly to use the curlies in this case, but
298 the BLOCK can contain any arbitrary expression, in particular,
299 subscripted expressions:
300
301     &{ $dispatch{$index} }(1,2,3);      # call correct routine
302
303 Because of being able to omit the curlies for the simple case of C<$$x>,
304 people often make the mistake of viewing the dereferencing symbols as
305 proper operators, and wonder about their precedence.  If they were,
306 though, you could use parentheses instead of braces.  That's not the case.
307 Consider the difference below; case 0 is a short-hand version of case 1,
308 I<NOT> case 2:
309
310     $$hashref{"KEY"}   = "VALUE";       # CASE 0
311     ${$hashref}{"KEY"} = "VALUE";       # CASE 1
312     ${$hashref{"KEY"}} = "VALUE";       # CASE 2
313     ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
314
315 Case 2 is also deceptive in that you're accessing a variable
316 called %hashref, not dereferencing through $hashref to the hash
317 it's presumably referencing.  That would be case 3.
318
319 =item 3.
320
321 Subroutine calls and lookups of individual array elements arise often
322 enough that it gets cumbersome to use method 2.  As a form of
323 syntactic sugar, the examples for method 2 may be written:
324
325     $arrayref->[0] = "January";   # Array element
326     $hashref->{"KEY"} = "VALUE";  # Hash element
327     $coderef->(1,2,3);            # Subroutine call
328
329 The left side of the arrow can be any expression returning a reference,
330 including a previous dereference.  Note that C<$array[$x]> is I<NOT> the
331 same thing as C<$array-E<gt>[$x]> here:
332
333     $array[$x]->{"foo"}->[0] = "January";
334
335 This is one of the cases we mentioned earlier in which references could
336 spring into existence when in an lvalue context.  Before this
337 statement, C<$array[$x]> may have been undefined.  If so, it's
338 automatically defined with a hash reference so that we can look up
339 C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
340 defined with an array reference so that we can look up C<[0]> in it.
341
342 One more thing here.  The arrow is optional I<BETWEEN> brackets
343 subscripts, so you can shrink the above down to
344
345     $array[$x]{"foo"}[0] = "January";
346
347 Which, in the degenerate case of using only ordinary arrays, gives you
348 multidimensional arrays just like C's:
349
350     $score[$x][$y][$z] += 42;
351
352 Well, okay, not entirely like C's arrays, actually.  C doesn't know how
353 to grow its arrays on demand.  Perl does.
354
355 =item 4.
356
357 If a reference happens to be a reference to an object, then there are
358 probably methods to access the things referred to, and you should probably
359 stick to those methods unless you're in the class package that defines the
360 object's methods.  In other words, be nice, and don't violate the object's
361 encapsulation without a very good reason.  Perl does not enforce
362 encapsulation.  We are not totalitarians here.  We do expect some basic
363 civility though.
364
365 =back
366
367 The ref() operator may be used to determine what type of thing the
368 reference is pointing to.  See L<perlfunc>.
369
370 The bless() operator may be used to associate a reference with a package
371 functioning as an object class.  See L<perlobj>.
372
373 A typeglob may be dereferenced the same way a reference can, because
374 the dereference syntax always indicates the kind of reference desired.
375 So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
376
377 Here's a trick for interpolating a subroutine call into a string:
378
379     print "My sub returned @{[mysub(1,2,3)]} that time.\n";
380
381 The way it works is that when the C<@{...}> is seen in the double-quoted
382 string, it's evaluated as a block.  The block creates a reference to an
383 anonymous array containing the results of the call to C<mysub(1,2,3)>.  So
384 the whole block returns a reference to an array, which is then
385 dereferenced by C<@{...}> and stuck into the double-quoted string. This
386 chicanery is also useful for arbitrary expressions:
387
388     print "That yields @{[$n + 5]} widgets\n";
389
390 =head2 Symbolic references
391
392 We said that references spring into existence as necessary if they are
393 undefined, but we didn't say what happens if a value used as a
394 reference is already defined, but I<ISN'T> a hard reference.  If you
395 use it as a reference in this case, it'll be treated as a symbolic
396 reference.  That is, the value of the scalar is taken to be the I<NAME>
397 of a variable, rather than a direct link to a (possibly) anonymous
398 value.
399
400 People frequently expect it to work like this.  So it does.
401
402     $name = "foo";
403     $$name = 1;                 # Sets $foo
404     ${$name} = 2;               # Sets $foo
405     ${$name x 2} = 3;           # Sets $foofoo
406     $name->[0] = 4;             # Sets $foo[0]
407     @$name = ();                # Clears @foo
408     &$name();                   # Calls &foo() (as in Perl 4)
409     $pack = "THAT";
410     ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
411
412 This is very powerful, and slightly dangerous, in that it's possible
413 to intend (with the utmost sincerity) to use a hard reference, and
414 accidentally use a symbolic reference instead.  To protect against
415 that, you can say
416
417     use strict 'refs';
418
419 and then only hard references will be allowed for the rest of the enclosing
420 block.  An inner block may countermand that with
421
422     no strict 'refs';
423
424 Only package variables are visible to symbolic references.  Lexical
425 variables (declared with my()) aren't in a symbol table, and thus are
426 invisible to this mechanism.  For example:
427
428     local($value) = 10;
429     $ref = \$value;
430     {
431         my $value = 20;
432         print $$ref;
433     }
434
435 This will still print 10, not 20.  Remember that local() affects package
436 variables, which are all "global" to the package.
437
438 =head2 Not-so-symbolic references
439
440 A new feature contributing to readability in perl version 5.001 is that the
441 brackets around a symbolic reference behave more like quotes, just as they
442 always have within a string.  That is,
443
444     $push = "pop on ";
445     print "${push}over";
446
447 has always meant to print "pop on over", despite the fact that push is
448 a reserved word.  This has been generalized to work the same outside
449 of quotes, so that
450
451     print ${push} . "over";
452
453 and even
454
455     print ${ push } . "over";
456
457 will have the same effect.  (This would have been a syntax error in
458 Perl 5.000, though Perl 4 allowed it in the spaceless form.)  Note that this
459 construct is I<not> considered to be a symbolic reference when you're
460 using strict refs:
461
462     use strict 'refs';
463     ${ bareword };      # Okay, means $bareword.
464     ${ "bareword" };    # Error, symbolic reference.
465
466 Similarly, because of all the subscripting that is done using single
467 words, we've applied the same rule to any bareword that is used for
468 subscripting a hash.  So now, instead of writing
469
470     $array{ "aaa" }{ "bbb" }{ "ccc" }
471
472 you can write just
473
474     $array{ aaa }{ bbb }{ ccc }
475
476 and not worry about whether the subscripts are reserved words.  In the
477 rare event that you do wish to do something like
478
479     $array{ shift }
480
481 you can force interpretation as a reserved word by adding anything that
482 makes it more than a bareword:
483
484     $array{ shift() }
485     $array{ +shift }
486     $array{ shift @_ }
487
488 The B<-w> switch will warn you if it interprets a reserved word as a string.
489 But it will no longer warn you about using lowercase words, because the
490 string is effectively quoted.
491
492 =head1 WARNING
493
494 You may not (usefully) use a reference as the key to a hash.  It will be
495 converted into a string:
496
497     $x{ \$a } = $a;
498
499 If you try to dereference the key, it won't do a hard dereference, and
500 you won't accomplish what you're attempting.  You might want to do something
501 more like
502
503     $r = \@a;
504     $x{ $r } = $r;
505
506 And then at least you can use the values(), which will be
507 real refs, instead of the keys(), which won't.
508
509 =head1 SEE ALSO
510
511 Besides the obvious documents, source code can be instructive.
512 Some rather pathological examples of the use of references can be found
513 in the F<t/op/ref.t> regression test in the Perl source directory.
514
515 See also L<perldsc> and L<perllol> for how to use references to create
516 complex data structures, and L<perlobj> for how to use them to create
517 objects.