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