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