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