This is my patch patch.1m for perl5.001.
[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 In Perl 4 it was difficult to represent complex data structures, because
8 all references had to be symbolic, and even that was difficult to do when
9 you wanted to refer to a variable rather than a symbol table entry.  Perl
10 5 not only makes it easier to use symbolic references to variables, but
11 lets you have "hard" references to any piece of data.  Any scalar may hold
12 a hard reference.  Since arrays and hashes contain scalars, you can now
13 easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays
14 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
18 goes to zero.  If that thing happens to be an object, the object is
19 destructed.  See L<perlobj> for more about objects.  (In a sense,
20 everything in Perl is an object, but we usually reserve the word for
21 references to objects that have been officially "blessed" into a class package.)
22
23 A symbolic reference contains the name of a variable, just as a
24 symbolic link in the filesystem merely contains the name of a file.  
25 The C<*glob> notation is a kind of symbolic reference.  Hard references
26 are more like hard links in the file system: merely another way
27 at getting at the same underlying object, irrespective of its name.
28
29 "Hard" references are easy to use in Perl.  There is just one
30 overriding principle:  Perl does no implicit referencing or
31 dereferencing.  When a scalar is holding a reference, it always behaves
32 as a scalar.  It doesn't magically start being an array or a hash
33 unless you tell it so explicitly by dereferencing it.
34
35 References can be constructed several ways.
36
37 =over 4
38
39 =item 1.
40
41 By using the backslash operator on a variable, subroutine, or value.
42 (This works much like the & (address-of) operator works in C.)  Note
43 that this typically creates I<ANOTHER> reference to a variable, since
44 there's already a reference to the variable in the symbol table.  But
45 the symbol table reference might go away, and you'll still have the
46 reference that the backslash returned.  Here are some examples:
47
48     $scalarref = \$foo;
49     $arrayref  = \@ARGV;
50     $hashref   = \%ENV;
51     $coderef   = \&handler;
52
53 =item 2.
54
55 A reference to an anonymous array can be constructed using square
56 brackets:
57
58     $arrayref = [1, 2, ['a', 'b', 'c']];
59
60 Here we've constructed a reference to an anonymous array of three elements
61 whose final element is itself reference to another anonymous array of three
62 elements.  (The multidimensional syntax described later can be used to
63 access this.  For example, after the above, $arrayref->[2][1] would have
64 the value "b".)
65
66 =item 3.
67
68 A reference to an anonymous hash can be constructed using curly
69 brackets:
70
71     $hashref = {
72         'Adam'  => 'Eve',
73         'Clyde' => 'Bonnie',
74     };
75
76 Anonymous hash and array constructors can be intermixed freely to
77 produce as complicated a structure as you want.  The multidimensional
78 syntax described below works for these too.  The values above are
79 literals, but variables and expressions would work just as well, because
80 assignment operators in Perl (even within local() or my()) are executable
81 statements, not compile-time declarations.
82
83 Because curly brackets (braces) are used for several other things
84 including BLOCKs, you may occasionally have to disambiguate braces at the
85 beginning of a statement by putting a C<+> or a C<return> in front so
86 that Perl realizes the opening brace isn't starting a BLOCK.  The economy and
87 mnemonic value of using curlies is deemed worth this occasional extra
88 hassle.
89
90 For example, if you wanted a function to make a new hash and return a
91 reference to it, you have these options:
92
93     sub hashem {        { @_ } }   # silently wrong
94     sub hashem {       +{ @_ } }   # ok
95     sub hashem { return { @_ } }   # ok
96
97 =item 4.
98
99 A reference to an anonymous subroutine can be constructed by using
100 C<sub> without a subname:
101
102     $coderef = sub { print "Boink!\n" };
103
104 Note the presence of the semicolon.  Except for the fact that the code
105 inside isn't executed immediately, a C<sub {}> is not so much a
106 declaration as it is an operator, like C<do{}> or C<eval{}>.  (However, no
107 matter how many times you execute that line (unless you're in an
108 C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
109 anonymous subroutine.)
110
111 Anonymous subroutines act as closures with respect to my() variables,
112 that is, variables visible lexically within the current scope.  Closure
113 is a notion out of the Lisp world that says if you define an anonymous
114 function in a particular lexical context, it pretends to run in that
115 context even when it's called outside of the context.
116
117 In human terms, it's a funny way of passing arguments to a subroutine when
118 you define it as well as when you call it.  It's useful for setting up
119 little bits of code to run later, such as callbacks.  You can even
120 do object-oriented stuff with it, though Perl provides a different
121 mechanism to do that already--see L<perlobj>.
122
123 You can also think of closure as a way to write a subroutine template without
124 using eval.  (In fact, in version 5.000, eval was the I<only> way to get
125 closures.  You may wish to use "require 5.001" if you use closures.)
126
127 Here's a small example of how closures works:
128
129     sub newprint {
130         my $x = shift;
131         return sub { my $y = shift; print "$x, $y!\n"; };
132     }
133     $h = newprint("Howdy");
134     $g = newprint("Greetings");
135
136     # Time passes...
137
138     &$h("world");
139     &$g("earthlings");
140
141 This prints
142
143     Howdy, world!
144     Greetings, earthlings!
145
146 Note particularly that $x continues to refer to the value passed into
147 newprint() *despite* the fact that the "my $x" has seemingly gone out of
148 scope by the time the anonymous subroutine runs.  That's what closure
149 is all about.
150
151 This only applies to lexical variables, by the way.  Dynamic variables
152 continue to work as they have always worked.  Closure is not something
153 that most Perl programmers need trouble themselves about to begin with.
154
155 =item 5.
156
157 References are often returned by special subroutines called constructors.
158 Perl objects are just references to a special kind of object that happens to know
159 which package it's associated with.  Constructors are just special
160 subroutines that know how to create that association.  They do so by
161 starting with an ordinary reference, and it remains an ordinary reference
162 even while it's also being an object.  Constructors are customarily
163 named new(), but don't have to be:
164
165     $objref = new Doggie (Tail => 'short', Ears => 'long');
166
167 =item 6.
168
169 References of the appropriate type can spring into existence if you
170 dereference them in a context that assumes they exist.  Since we haven't
171 talked about dereferencing yet, we can't show you any examples yet.
172
173 =back
174
175 That's it for creating references.  By now you're probably dying to
176 know how to use references to get back to your long-lost data.  There
177 are several basic methods.
178
179 =over 4
180
181 =item 1.
182
183 Anywhere you'd put an identifier as part of a variable or subroutine
184 name, you can replace the identifier with a simple scalar variable
185 containing a reference of the correct type:
186
187     $bar = $$scalarref;
188     push(@$arrayref, $filename);
189     $$arrayref[0] = "January";
190     $$hashref{"KEY"} = "VALUE";
191     &$coderef(1,2,3);
192
193 It's important to understand that we are specifically I<NOT> dereferencing
194 C<$arrayref[0]> or C<$hashref{"KEY"}> there.  The dereference of the
195 scalar variable happens I<BEFORE> it does any key lookups.  Anything more
196 complicated than a simple scalar variable must use methods 2 or 3 below.
197 However, a "simple scalar" includes an identifier that itself uses method
198 1 recursively.  Therefore, the following prints "howdy".
199
200     $refrefref = \\\"howdy";
201     print $$$$refrefref;
202
203 =item 2.
204
205 Anywhere you'd put an identifier as part of a variable or subroutine
206 name, you can replace the identifier with a BLOCK returning a reference
207 of the correct type.  In other words, the previous examples could be
208 written like this:
209
210     $bar = ${$scalarref};
211     push(@{$arrayref}, $filename);
212     ${$arrayref}[0] = "January";
213     ${$hashref}{"KEY"} = "VALUE";
214     &{$coderef}(1,2,3);
215
216 Admittedly, it's a little silly to use the curlies in this case, but
217 the BLOCK can contain any arbitrary expression, in particular,
218 subscripted expressions:
219
220     &{ $dispatch{$index} }(1,2,3);      # call correct routine 
221
222 Because of being able to omit the curlies for the simple case of C<$$x>,
223 people often make the mistake of viewing the dereferencing symbols as
224 proper operators, and wonder about their precedence.  If they were,
225 though, you could use parens instead of braces.  That's not the case.
226 Consider the difference below; case 0 is a short-hand version of case 1,
227 I<NOT> case 2:
228
229     $$hashref{"KEY"}   = "VALUE";       # CASE 0
230     ${$hashref}{"KEY"} = "VALUE";       # CASE 1
231     ${$hashref{"KEY"}} = "VALUE";       # CASE 2
232     ${$hashref->{"KEY"}} = "VALUE";     # CASE 3
233
234 Case 2 is also deceptive in that you're accessing a variable
235 called %hashref, not dereferencing through $hashref to the hash
236 it's presumably referencing.  That would be case 3.
237
238 =item 3.
239
240 The case of individual array elements arises often enough that it gets
241 cumbersome to use method 2.  As a form of syntactic sugar, the two
242 lines like that above can be written:
243
244     $arrayref->[0] = "January";
245     $hashref->{"KEY"} = "VALUE";
246
247 The left side of the array can be any expression returning a reference,
248 including a previous dereference.  Note that C<$array[$x]> is I<NOT> the
249 same thing as C<$array-E<gt>[$x]> here:
250
251     $array[$x]->{"foo"}->[0] = "January";
252
253 This is one of the cases we mentioned earlier in which references could
254 spring into existence when in an lvalue context.  Before this
255 statement, C<$array[$x]> may have been undefined.  If so, it's
256 automatically defined with a hash reference so that we can look up
257 C<{"foo"}> in it.  Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
258 defined with an array reference so that we can look up C<[0]> in it.
259
260 One more thing here.  The arrow is optional I<BETWEEN> brackets
261 subscripts, so you can shrink the above down to
262
263     $array[$x]{"foo"}[0] = "January";
264
265 Which, in the degenerate case of using only ordinary arrays, gives you
266 multidimensional arrays just like C's:
267
268     $score[$x][$y][$z] += 42;
269
270 Well, okay, not entirely like C's arrays, actually.  C doesn't know how
271 to grow its arrays on demand.  Perl does.
272
273 =item 4.
274
275 If a reference happens to be a reference to an object, then there are
276 probably methods to access the things referred to, and you should probably
277 stick to those methods unless you're in the class package that defines the
278 object's methods.  In other words, be nice, and don't violate the object's
279 encapsulation without a very good reason.  Perl does not enforce
280 encapsulation.  We are not totalitarians here.  We do expect some basic
281 civility though.
282
283 =back
284
285 The ref() operator may be used to determine what type of thing the
286 reference is pointing to.  See L<perlfunc>.
287
288 The bless() operator may be used to associate a reference with a package
289 functioning as an object class.  See L<perlobj>.
290
291 A type glob may be dereferenced the same way a reference can, since
292 the dereference syntax always indicates the kind of reference desired.
293 So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
294
295 Here's a trick for interpolating a subroutine call into a string:
296
297     print "My sub returned ${\mysub(1,2,3)}\n";
298
299 The way it works is that when the C<${...}> is seen in the double-quoted
300 string, it's evaluated as a block.  The block executes the call to
301 C<mysub(1,2,3)>, and then takes a reference to that.  So the whole block
302 returns a reference to a scalar, which is then dereferenced by C<${...}>
303 and stuck into the double-quoted string.
304
305 =head2 Symbolic references
306
307 We said that references spring into existence as necessary if they are
308 undefined, but we didn't say what happens if a value used as a
309 reference is already defined, but I<ISN'T> a hard reference.  If you
310 use it as a reference in this case, it'll be treated as a symbolic
311 reference.  That is, the value of the scalar is taken to be the I<NAME>
312 of a variable, rather than a direct link to a (possibly) anonymous
313 value.
314
315 People frequently expect it to work like this.  So it does.
316
317     $name = "foo";
318     $$name = 1;                 # Sets $foo
319     ${$name} = 2;               # Sets $foo
320     ${$name x 2} = 3;           # Sets $foofoo
321     $name->[0] = 4;             # Sets $foo[0]
322     @$name = ();                # Clears @foo
323     &$name();                   # Calls &foo() (as in Perl 4)
324     $pack = "THAT";
325     ${"${pack}::$name"} = 5;    # Sets $THAT::foo without eval
326
327 This is very powerful, and slightly dangerous, in that it's possible
328 to intend (with the utmost sincerity) to use a hard reference, and
329 accidentally use a symbolic reference instead.  To protect against
330 that, you can say
331
332     use strict 'refs';
333
334 and then only hard references will be allowed for the rest of the enclosing
335 block.  An inner block may countermand that with 
336
337     no strict 'refs';
338
339 Only package variables are visible to symbolic references.  Lexical
340 variables (declared with my()) aren't in a symbol table, and thus are
341 invisible to this mechanism.  For example:
342
343     local($value) = 10;
344     $ref = \$value;
345     {
346         my $value = 20;
347         print $$ref;
348     } 
349
350 This will still print 10, not 20.  Remember that local() affects package
351 variables, which are all "global" to the package.
352
353 =head2 Not-so-symbolic references
354
355 A new feature contributing to readability in 5.001 is that the brackets
356 around a symbolic reference behave more like quotes, just as they
357 always have within a string.  That is,
358
359     $push = "pop on ";
360     print "${push}over";
361
362 has always meant to print "pop on over", despite the fact that push is
363 a reserved word.  This has been generalized to work the same outside
364 of quotes, so that
365
366     print ${push} . "over";
367
368 and even
369
370     print ${ push } . "over";
371
372 will have the same effect.  (This would have been a syntax error in
373 5.000, though Perl 4 allowed it in the spaceless form.)  Note that this
374 construct is I<not> considered to be a symbolic reference when you're
375 using strict refs:
376
377     use strict 'refs';
378     ${ bareword };      # Okay, means $bareword.
379     ${ "bareword" };    # Error, symbolic reference.
380
381 Similarly, because of all the subscripting that is done using single
382 words, we've applied the same rule to any bareword that is used for
383 subscripting a hash.  So now, instead of writing
384
385     $array{ "aaa" }{ "bbb" }{ "ccc" }
386
387 you can just write
388
389     $array{ aaa }{ bbb }{ ccc }
390
391 and not worry about whether the subscripts are reserved words.  In the
392 rare event that you do wish to do something like
393
394     $array{ shift }
395
396 you can force interpretation as a reserved word by adding anything that
397 makes it more than a bareword:
398
399     $array{ shift() }
400     $array{ +shift }
401     $array{ shift @_ }
402
403 The B<-w> switch will warn you if it interprets a reserved word as a string.
404 But it will no longer warn you about using lowercase words, since the
405 string is effectively quoted.
406
407 =head2 WARNING
408
409 You may not (usefully) use a reference as the key to a hash.  It will be
410 converted into a string:
411
412     $x{ \$a } = $a;
413
414 If you try to dereference the key, it won't do a hard dereference, and 
415 you won't accomplish what you're attemping.
416
417 =head2 Further Reading
418
419 Besides the obvious documents, source code can be instructive.
420 Some rather pathological examples of the use of references can be found
421 in the F<t/op/ref.t> regression test in the Perl source directory.