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