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