This is a live mirror of the Perl 5 development currently hosted at
perl5.000 patch.0o: [address] a few more Configure and build nits.
[perl5.git] / pod / perlref.pod
1=head1 NAME
3perlref - Perl references and nested data structures
7In Perl 4 it was difficult to represent complex data structures, because
8all references had to be symbolic, and even that was difficult to do when
9you wanted to refer to a variable rather than a symbol table entry. Perl
105 not only makes it easier to use symbolic references to variables, but
11lets you have "hard" references to any piece of data. Any scalar may hold
12a hard reference. Since arrays and hashes contain scalars, you can now
13easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays
14of hashes of functions, and so on.
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.)
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.
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.
35References can be constructed several ways.
37=over 4
39=item 1.
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:
48 $scalarref = \$foo;
49 $arrayref = \@ARGV;
50 $hashref = \%ENV;
51 $coderef = \&handler;
53=item 2.
55A reference to an anonymous array can be constructed using square
58 $arrayref = [1, 2, ['a', 'b', 'c']];
60Here we've constructed a reference to an anonymous array of three elements
61whose final element is itself reference to another anonymous array of three
62elements. (The multidimensional syntax described later can be used to
63access this. For example, after the above, $arrayref->[2][1] would have
64the value "b".)
66=item 3.
68A reference to an anonymous hash can be constructed using curly
71 $hashref = {
72 'Adam' => 'Eve',
73 'Clyde' => 'Bonnie',
74 };
76Anonymous hash and array constructors can be intermixed freely to
77produce as complicated a structure as you want. The multidimensional
78syntax described below works for these too. The values above are
79literals, but variables and expressions would work just as well, because
80assignment operators in Perl (even within local() or my()) are executable
81statements, not compile-time declarations.
83Because curly brackets (braces) are used for several other things
84including BLOCKs, you may occasionally have to disambiguate braces at the
85beginning of a statement by putting a C<+> or a C<return> in front so
86that Perl realizes the opening brace isn't starting a BLOCK. The economy and
87mnemonic value of using curlies is deemed worth this occasional extra
90For example, if you wanted a function to make a new hash and return a
91reference to it, you have these options:
93 sub hashem { { @_ } } # silently wrong
94 sub hashem { +{ @_ } } # ok
95 sub hashem { return { @_ } } # ok
97=item 4.
99A reference to an anonymous subroutine can be constructed by using
100C<sub> without a subname:
102 $coderef = sub { print "Boink!\n" };
104Note the presence of the semicolon. Except for the fact that the code
105inside isn't executed immediately, a C<sub {}> is not so much a
106declaration as it is an operator, like C<do{}> or C<eval{}>. (However, no
107matter how many times you execute that line (unless you're in an
108C<eval("...")>), C<$coderef> will still have a reference to the I<SAME>
109anonymous subroutine.)
111For those who worry about these things, the current implementation
112uses shallow binding of local() variables; my() variables are not
113accessible. This precludes true closures. However, you can work
114around this with a run-time (rather than a compile-time) eval():
116 {
117 my $x = time;
118 $coderef = eval "sub { \$x }";
119 }
121Normally--if you'd used just C<sub{}> or even C<eval{}>--your unew sub
122would only have been able to access the global $x. But because you've
123used a run-time eval(), this will not only generate a brand new subroutine
124reference each time called, it will all grant access to the my() variable
125lexically above it rather than the global one. The particular $x
126accessed will be different for each new sub you create. This mechanism
127yields deep binding of variables. (If you don't know what closures, deep
128binding, or shallow binding are, don't worry too much about it.)
130=item 5.
132References are often returned by special subroutines called constructors.
133Perl objects are just reference a special kind of object that happens to know
134which package it's associated with. Constructors are just special
135subroutines that know how to create that association. They do so by
136starting with an ordinary reference, and it remains an ordinary reference
137even while it's also being an object. Constructors are customarily
138named new(), but don't have to be:
140 $objref = new Doggie (Tail => 'short', Ears => 'long');
142=item 6.
144References of the appropriate type can spring into existence if you
145dereference them in a context that assumes they exist. Since we haven't
146talked about dereferencing yet, we can't show you any examples yet.
150That's it for creating references. By now you're probably dying to
151know how to use references to get back to your long-lost data. There
152are several basic methods.
154=over 4
156=item 1.
158Anywhere you'd put an identifier as part of a variable or subroutine
159name, you can replace the identifier with a simple scalar variable
160containing a reference of the correct type:
162 $bar = $$scalarref;
163 push(@$arrayref, $filename);
164 $$arrayref[0] = "January";
165 $$hashref{"KEY"} = "VALUE";
166 &$coderef(1,2,3);
168It's important to understand that we are specifically I<NOT> dereferencing
169C<$arrayref[0]> or C<$hashref{"KEY"}> there. The dereference of the
170scalar variable happens I<BEFORE> it does any key lookups. Anything more
171complicated than a simple scalar variable must use methods 2 or 3 below.
172However, a "simple scalar" includes an identifier that itself uses method
1731 recursively. Therefore, the following prints "howdy".
175 $refrefref = \\\"howdy";
176 print $$$$refrefref;
178=item 2.
180Anywhere you'd put an identifier as part of a variable or subroutine
181name, you can replace the identifier with a BLOCK returning a reference
182of the correct type. In other words, the previous examples could be
183written like this:
185 $bar = ${$scalarref};
186 push(@{$arrayref}, $filename);
187 ${$arrayref}[0] = "January";
188 ${$hashref}{"KEY"} = "VALUE";
189 &{$coderef}(1,2,3);
191Admittedly, it's a little silly to use the curlies in this case, but
192the BLOCK can contain any arbitrary expression, in particular,
193subscripted expressions:
195 &{ $dispatch{$index} }(1,2,3); # call correct routine
197Because of being able to omit the curlies for the simple case of C<$$x>,
198people often make the mistake of viewing the dereferencing symbols as
199proper operators, and wonder about their precedence. If they were,
200though, you could use parens instead of braces. That's not the case.
201Consider the difference below; case 0 is a short-hand version of case 1,
202I<NOT> case 2:
204 $$hashref{"KEY"} = "VALUE"; # CASE 0
205 ${$hashref}{"KEY"} = "VALUE"; # CASE 1
206 ${$hashref{"KEY"}} = "VALUE"; # CASE 2
207 ${$hashref->{"KEY"}} = "VALUE"; # CASE 3
209Case 2 is also deceptive in that you're accessing a variable
210called %hashref, not dereferencing through $hashref to the hash
211it's presumably referencing. That would be case 3.
213=item 3.
215The case of individual array elements arises often enough that it gets
216cumbersome to use method 2. As a form of syntactic sugar, the two
217lines like that above can be written:
219 $arrayref->[0] = "January";
220 $hashref->{"KEY} = "VALUE";
222The left side of the array can be any expression returning a reference,
223including a previous dereference. Note that C<$array[$x]> is I<NOT> the
224same thing as C<$array-E<gt>[$x]> here:
226 $array[$x]->{"foo"}->[0] = "January";
228This is one of the cases we mentioned earlier in which references could
229spring into existence when in an lvalue context. Before this
230statement, C<$array[$x]> may have been undefined. If so, it's
231automatically defined with a hash reference so that we can look up
232C<{"foo"}> in it. Likewise C<$array[$x]-E<gt>{"foo"}> will automatically get
233defined with an array reference so that we can look up C<[0]> in it.
235One more thing here. The arrow is optional I<BETWEEN> brackets
236subscripts, so you can shrink the above down to
238 $array[$x]{"foo"}[0] = "January";
240Which, in the degenerate case of using only ordinary arrays, gives you
241multidimensional arrays just like C's:
243 $score[$x][$y][$z] += 42;
245Well, okay, not entirely like C's arrays, actually. C doesn't know how
246to grow its arrays on demand. Perl does.
248=item 4.
250If a reference happens to be a reference to an object, then there are
251probably methods to access the things referred to, and you should probably
252stick to those methods unless you're in the class package that defines the
253object's methods. In other words, be nice, and don't violate the object's
254encapsulation without a very good reason. Perl does not enforce
255encapsulation. We are not totalitarians here. We do expect some basic
256civility though.
260The ref() operator may be used to determine what type of thing the
261reference is pointing to. See L<perlfunc>.
263The bless() operator may be used to associate a reference with a package
264functioning as an object class. See L<perlobj>.
266A type glob may be dereferenced the same way a reference can, since
267the dereference syntax always indicates the kind of reference desired.
268So C<${*foo}> and C<${\$foo}> both indicate the same scalar variable.
270Here's a trick for interpolating a subroutine call into a string:
272 print "My sub returned ${\mysub(1,2,3)}\n";
274The way it works is that when the C<${...}> is seen in the double-quoted
275string, it's evaluated as a block. The block executes the call to
276C<mysub(1,2,3)>, and then takes a reference to that. So the whole block
277returns a reference to a scalar, which is then dereferenced by C<${...}>
278and stuck into the double-quoted string.
280=head2 Symbolic references
282We said that references spring into existence as necessary if they are
283undefined, but we didn't say what happens if a value used as a
284reference is already defined, but I<ISN'T> a hard reference. If you
285use it as a reference in this case, it'll be treated as a symbolic
286reference. That is, the value of the scalar is taken to be the I<NAME>
287of a variable, rather than a direct link to a (possibly) anonymous
290People frequently expect it to work like this. So it does.
292 $name = "foo";
293 $$name = 1; # Sets $foo
294 ${$name} = 2; # Sets $foo
295 ${$name x 2} = 3; # Sets $foofoo
296 $name->[0] = 4; # Sets $foo[0]
297 @$name = (); # Clears @foo
298 &$name(); # Calls &foo() (as in Perl 4)
299 $pack = "THAT";
300 ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval
302This is very powerful, and slightly dangerous, in that it's possible
303to intend (with the utmost sincerity) to use a hard reference, and
304accidentally use a symbolic reference instead. To protect against
305that, you can say
307 use strict 'refs';
309and then only hard references will be allowed for the rest of the enclosing
310block. An inner block may countermand that with
312 no strict 'refs';
314Only package variables are visible to symbolic references. Lexical
315variables (declared with my()) aren't in a symbol table, and thus are
316invisible to this mechanism. For example:
318 local($value) = 10;
319 $ref = \$value;
320 {
321 my $value = 20;
322 print $$ref;
323 }
325This will still print 10, not 20. Remember that local() affects package
326variables, which are all "global" to the package.
328=head2 Further Reading
330Besides the obvious documents, source code can be instructive.
331Some rather pathological examples of the use of references can be found
332in the F<t/op/ref.t> regression test in the Perl source directory.