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