Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perlref.html
blob61274139cd3dc99b4815c43ee9a27fda477ae5c0
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perlref - Perl references and nested data structures</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perlref - Perl references and nested data structures</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#note">NOTE</a></li>
24 <li><a href="#description">DESCRIPTION</a></li>
25 <ul>
27 <li><a href="#making_references">Making References</a></li>
28 <li><a href="#using_references">Using References</a></li>
29 <li><a href="#symbolic_references">Symbolic references</a></li>
30 <li><a href="#notsosymbolic_references">Not-so-symbolic references</a></li>
31 <li><a href="#pseudohashes__using_an_array_as_a_hash">Pseudo-hashes: Using an array as a hash</a></li>
32 <li><a href="#function_templates">Function Templates</a></li>
33 </ul>
35 <li><a href="#warning">WARNING</a></li>
36 <li><a href="#see_also">SEE ALSO</a></li>
37 </ul>
38 <!-- INDEX END -->
40 <hr />
41 <p>
42 </p>
43 <h1><a name="name_x_reference__x_pointer__x_data_structure__x_structure__x_struct_">NAME
44 </a></h1>
45 <p>perlref - Perl references and nested data structures</p>
46 <p>
47 </p>
48 <hr />
49 <h1><a name="note">NOTE</a></h1>
50 <p>This is complete documentation about all aspects of references.
51 For a shorter, tutorial introduction to just the essential features,
52 see <a href="file://C|\msysgit\mingw\html/pod/perlreftut.html">the perlreftut manpage</a>.</p>
53 <p>
54 </p>
55 <hr />
56 <h1><a name="description">DESCRIPTION</a></h1>
57 <p>Before release 5 of Perl it was difficult to represent complex data
58 structures, because all references had to be symbolic--and even then
59 it was difficult to refer to a variable instead of a symbol table entry.
60 Perl now not only makes it easier to use symbolic references to variables,
61 but also lets you have ``hard'' references to any piece of data or code.
62 Any scalar may hold a hard reference. Because arrays and hashes contain
63 scalars, you can now easily build arrays of arrays, arrays of hashes,
64 hashes of arrays, arrays of hashes of functions, and so on.</p>
65 <p>Hard references are smart--they keep track of reference counts for you,
66 automatically freeing the thing referred to when its reference count goes
67 to zero. (Reference counts for values in self-referential or
68 cyclic data structures may not go to zero without a little help; see
69 <a href="file://C|\msysgit\mingw\html/pod/perlobj.html#twophased_garbage_collection">Two-Phased Garbage Collection in the perlobj manpage</a> for a detailed explanation.)
70 If that thing happens to be an object, the object is destructed. See
71 <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a> for more about objects. (In a sense, everything in Perl is an
72 object, but we usually reserve the word for references to objects that
73 have been officially ``blessed'' into a class package.)</p>
74 <p>Symbolic references are names of variables or other objects, just as a
75 symbolic link in a Unix filesystem contains merely the name of a file.
76 The <code>*glob</code> notation is something of a symbolic reference. (Symbolic
77 references are sometimes called ``soft references'', but please don't call
78 them that; references are confusing enough without useless synonyms.)
80 </p>
81 <p>In contrast, hard references are more like hard links in a Unix file
82 system: They are used to access an underlying object without concern for
83 what its (other) name is. When the word ``reference'' is used without an
84 adjective, as in the following paragraph, it is usually talking about a
85 hard reference.
86 </p>
87 <p>References are easy to use in Perl. There is just one overriding
88 principle: Perl does no implicit referencing or dereferencing. When a
89 scalar is holding a reference, it always behaves as a simple scalar. It
90 doesn't magically start being an array or hash or subroutine; you have to
91 tell it explicitly to do so, by dereferencing it.</p>
92 <p>
93 </p>
94 <h2><a name="making_references_x_reference__creation__x_referencing_">Making References
95 </a></h2>
96 <p>References can be created in several ways.</p>
97 <ol>
98 <li><strong><a name="item_x_3c_5c_3e_x_3cbackslash_3e"> </a></strong>
100 <p>By using the backslash operator on a variable, subroutine, or value.
101 (This works much like the &amp; (address-of) operator in C.)
102 This typically creates <em>another</em> reference to a variable, because
103 there's already a reference to the variable in the symbol table. But
104 the symbol table reference might go away, and you'll still have the
105 reference that the backslash returned. Here are some examples:</p>
106 <pre>
107 $scalarref = \$foo;
108 $arrayref = \@ARGV;
109 $hashref = \%ENV;
110 $coderef = \&amp;handler;
111 $globref = \*foo;</pre>
112 <p>It isn't possible to create a true reference to an IO handle (filehandle
113 or dirhandle) using the backslash operator. The most you can get is a
114 reference to a typeglob, which is actually a complete symbol table entry.
115 But see the explanation of the <code>*foo{THING}</code> syntax below. However,
116 you can still use type globs and globrefs as though they were IO handles.</p>
117 </li>
118 <li><strong><a name="item_x_3carray_2c_anonymous_3e_x_3c_5b_3e_x_3c_5b_5d_3e">
119 </a></strong>
121 <p>A reference to an anonymous array can be created using square
122 brackets:</p>
123 <pre>
124 $arrayref = [1, 2, ['a', 'b', 'c']];</pre>
125 <p>Here we've created a reference to an anonymous array of three elements
126 whose final element is itself a reference to another anonymous array of three
127 elements. (The multidimensional syntax described later can be used to
128 access this. For example, after the above, <code>$arrayref-&gt;[2][1]</code> would have
129 the value ``b''.)</p>
130 <p>Taking a reference to an enumerated list is not the same
131 as using square brackets--instead it's the same as creating
132 a list of references!</p>
133 <pre>
134 @list = (\$a, \@b, \%c);
135 @list = \($a, @b, %c); # same thing!</pre>
136 <p>As a special case, <code>\(@foo)</code> returns a list of references to the contents
137 of <code>@foo</code>, not a reference to <code>@foo</code> itself. Likewise for <code>%foo</code>,
138 except that the key references are to copies (since the keys are just
139 strings rather than full-fledged scalars).</p>
140 </li>
141 <li><strong><a name="item_x_3chash_2c_anonymous_3e_x_3c_7b_3e_x_3c_7b_7d_3e_">
142 </a></strong>
144 <p>A reference to an anonymous hash can be created using curly
145 brackets:</p>
146 <pre>
147 $hashref = {
148 'Adam' =&gt; 'Eve',
149 'Clyde' =&gt; 'Bonnie',
150 };</pre>
151 <p>Anonymous hash and array composers like these can be intermixed freely to
152 produce as complicated a structure as you want. The multidimensional
153 syntax described below works for these too. The values above are
154 literals, but variables and expressions would work just as well, because
155 assignment operators in Perl (even within <code>local()</code> or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my())</code></a> are executable
156 statements, not compile-time declarations.</p>
157 <p>Because curly brackets (braces) are used for several other things
158 including BLOCKs, you may occasionally have to disambiguate braces at the
159 beginning of a statement by putting a <code>+</code> or a <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_return"><code>return</code></a> in front so
160 that Perl realizes the opening brace isn't starting a BLOCK. The economy and
161 mnemonic value of using curlies is deemed worth this occasional extra
162 hassle.</p>
163 <p>For example, if you wanted a function to make a new hash and return a
164 reference to it, you have these options:</p>
165 <pre>
166 sub hashem { { @_ } } # silently wrong
167 sub hashem { +{ @_ } } # ok
168 sub hashem { return { @_ } } # ok</pre>
169 <p>On the other hand, if you want the other meaning, you can do this:</p>
170 <pre>
171 sub showem { { @_ } } # ambiguous (currently ok, but may change)
172 sub showem { {; @_ } } # ok
173 sub showem { { return @_ } } # ok</pre>
174 <p>The leading <code>+{</code> and <code>{;</code> always serve to disambiguate
175 the expression to mean either the HASH reference, or the BLOCK.</p>
176 </li>
177 <li><strong><a name="item_x_3csubroutine_2c_anonymous_3e_x_3csubroutine_2c_r">
178 </a></strong>
180 <p>A reference to an anonymous subroutine can be created by using
181 <code>sub</code> without a subname:</p>
182 <pre>
183 $coderef = sub { print &quot;Boink!\n&quot; };</pre>
184 <p>Note the semicolon. Except for the code
185 inside not being immediately executed, a <code>sub {}</code> is not so much a
186 declaration as it is an operator, like <code>do{}</code> or <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval{}</code></a>. (However, no
187 matter how many times you execute that particular line (unless you're in an
188 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_eval"><code>eval(&quot;...&quot;)</code></a>), $coderef will still have a reference to the <em>same</em>
189 anonymous subroutine.)</p>
190 <p>Anonymous subroutines act as closures with respect to <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> variables,
191 that is, variables lexically visible within the current scope. Closure
192 is a notion out of the Lisp world that says if you define an anonymous
193 function in a particular lexical context, it pretends to run in that
194 context even when it's called outside the context.</p>
195 <p>In human terms, it's a funny way of passing arguments to a subroutine when
196 you define it as well as when you call it. It's useful for setting up
197 little bits of code to run later, such as callbacks. You can even
198 do object-oriented stuff with it, though Perl already provides a different
199 mechanism to do that--see <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>.</p>
200 <p>You might also think of closure as a way to write a subroutine
201 template without using eval(). Here's a small example of how
202 closures work:</p>
203 <pre>
204 sub newprint {
205 my $x = shift;
206 return sub { my $y = shift; print &quot;$x, $y!\n&quot;; };
208 $h = newprint(&quot;Howdy&quot;);
209 $g = newprint(&quot;Greetings&quot;);</pre>
210 <pre>
211 # Time passes...</pre>
212 <pre>
213 &amp;$h(&quot;world&quot;);
214 &amp;$g(&quot;earthlings&quot;);</pre>
215 <p>This prints</p>
216 <pre>
217 Howdy, world!
218 Greetings, earthlings!</pre>
219 <p>Note particularly that $x continues to refer to the value passed
220 into <code>newprint()</code> <em>despite</em> ``my $x'' having gone out of scope by the
221 time the anonymous subroutine runs. That's what a closure is all
222 about.</p>
223 <p>This applies only to lexical variables, by the way. Dynamic variables
224 continue to work as they have always worked. Closure is not something
225 that most Perl programmers need trouble themselves about to begin with.</p>
226 </li>
227 <li><strong><a name="item_x_3cconstructor_3e_x_3cnew_3e"> </a></strong>
229 <p>References are often returned by special subroutines called constructors.
230 Perl objects are just references to a special type of object that happens to know
231 which package it's associated with. Constructors are just special
232 subroutines that know how to create that association. They do so by
233 starting with an ordinary reference, and it remains an ordinary reference
234 even while it's also being an object. Constructors are often
235 named <code>new()</code> and called indirectly:</p>
236 <pre>
237 $objref = new Doggie (Tail =&gt; 'short', Ears =&gt; 'long');</pre>
238 <p>But don't have to be:</p>
239 <pre>
240 $objref = Doggie-&gt;new(Tail =&gt; 'short', Ears =&gt; 'long');</pre>
241 <pre>
242 use Term::Cap;
243 $terminal = Term::Cap-&gt;Tgetent( { OSPEED =&gt; 9600 });</pre>
244 <pre>
245 use Tk;
246 $main = MainWindow-&gt;new();
247 $menubar = $main-&gt;Frame(-relief =&gt; &quot;raised&quot;,
248 -borderwidth =&gt; 2)</pre>
249 </li>
250 <li><strong><a name="item_x_3cautovivification_3e"></a></strong>
252 <p>References of the appropriate type can spring into existence if you
253 dereference them in a context that assumes they exist. Because we haven't
254 talked about dereferencing yet, we can't show you any examples yet.</p>
255 </li>
256 <li><strong><a name="item_x_3c_2afoo_7bthing_7d_3e_x_3c_2a_3e"> </a></strong>
258 <p>A reference can be created by using a special syntax, lovingly known as
259 the *foo{THING} syntax. *foo{THING} returns a reference to the THING
260 slot in *foo (which is the symbol table entry which holds everything
261 known as foo).</p>
262 <pre>
263 $scalarref = *foo{SCALAR};
264 $arrayref = *ARGV{ARRAY};
265 $hashref = *ENV{HASH};
266 $coderef = *handler{CODE};
267 $ioref = *STDIN{IO};
268 $globref = *foo{GLOB};
269 $formatref = *foo{FORMAT};</pre>
270 <p>All of these are self-explanatory except for <code>*foo{IO}</code>. It returns
271 the IO handle, used for file handles (<a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_open">open in the perlfunc manpage</a>), sockets
272 (<a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#socket">socket in the perlfunc manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#socketpair">socketpair in the perlfunc manpage</a>), and directory
273 handles (<a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#opendir">opendir in the perlfunc manpage</a>). For compatibility with previous
274 versions of Perl, <code>*foo{FILEHANDLE}</code> is a synonym for <code>*foo{IO}</code>, though it
275 is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn
276 of its use.</p>
277 <p><code>*foo{THING}</code> returns undef if that particular THING hasn't been used yet,
278 except in the case of scalars. <code>*foo{SCALAR}</code> returns a reference to an
279 anonymous scalar if $foo hasn't been used yet. This might change in a
280 future release.</p>
281 <p><code>*foo{IO}</code> is an alternative to the <code>*HANDLE</code> mechanism given in
282 <a href="file://C|\msysgit\mingw\html/pod/perldata.html#typeglobs_and_filehandles">Typeglobs and Filehandles in the perldata manpage</a> for passing filehandles
283 into or out of subroutines, or storing into larger data structures.
284 Its disadvantage is that it won't create a new filehandle for you.
285 Its advantage is that you have less risk of clobbering more than
286 you want to with a typeglob assignment. (It still conflates file
287 and directory handles, though.) However, if you assign the incoming
288 value to a scalar instead of a typeglob as we do in the examples
289 below, there's no risk of that happening.</p>
290 <pre>
291 splutter(*STDOUT); # pass the whole glob
292 splutter(*STDOUT{IO}); # pass both file and dir handles</pre>
293 <pre>
294 sub splutter {
295 my $fh = shift;
296 print $fh &quot;her um well a hmmm\n&quot;;
297 }</pre>
298 <pre>
299 $rec = get_rec(*STDIN); # pass the whole glob
300 $rec = get_rec(*STDIN{IO}); # pass both file and dir handles</pre>
301 <pre>
302 sub get_rec {
303 my $fh = shift;
304 return scalar &lt;$fh&gt;;
305 }</pre>
306 </li>
307 </ol>
309 </p>
310 <h2><a name="using_references_x_reference__use__x_dereferencing__x_dereference_">Using References
311 </a></h2>
312 <p>That's it for creating references. By now you're probably dying to
313 know how to use references to get back to your long-lost data. There
314 are several basic methods.</p>
315 <ol>
316 <li>
317 <p>Anywhere you'd put an identifier (or chain of identifiers) as part
318 of a variable or subroutine name, you can replace the identifier with
319 a simple scalar variable containing a reference of the correct type:</p>
320 <pre>
321 $bar = $$scalarref;
322 push(@$arrayref, $filename);
323 $$arrayref[0] = &quot;January&quot;;
324 $$hashref{&quot;KEY&quot;} = &quot;VALUE&quot;;
325 &amp;$coderef(1,2,3);
326 print $globref &quot;output\n&quot;;</pre>
327 <p>It's important to understand that we are specifically <em>not</em> dereferencing
328 <code>$arrayref[0]</code> or <code>$hashref{&quot;KEY&quot;}</code> there. The dereference of the
329 scalar variable happens <em>before</em> it does any key lookups. Anything more
330 complicated than a simple scalar variable must use methods 2 or 3 below.
331 However, a ``simple scalar'' includes an identifier that itself uses method
332 1 recursively. Therefore, the following prints ``howdy''.</p>
333 <pre>
334 $refrefref = \\\&quot;howdy&quot;;
335 print $$$$refrefref;</pre>
336 </li>
337 <li><strong><a name="item_x_3c_24_7b_7d_3e_x_3c_40_7b_7d_3e_x_3c_25_7b_7d_3e"> </a></strong>
339 <p>Anywhere you'd put an identifier (or chain of identifiers) as part of a
340 variable or subroutine name, you can replace the identifier with a
341 BLOCK returning a reference of the correct type. In other words, the
342 previous examples could be written like this:</p>
343 <pre>
344 $bar = ${$scalarref};
345 push(@{$arrayref}, $filename);
346 ${$arrayref}[0] = &quot;January&quot;;
347 ${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;;
348 &amp;{$coderef}(1,2,3);
349 $globref-&gt;print(&quot;output\n&quot;); # iff IO::Handle is loaded</pre>
350 <p>Admittedly, it's a little silly to use the curlies in this case, but
351 the BLOCK can contain any arbitrary expression, in particular,
352 subscripted expressions:</p>
353 <pre>
354 &amp;{ $dispatch{$index} }(1,2,3); # call correct routine</pre>
355 <p>Because of being able to omit the curlies for the simple case of <code>$$x</code>,
356 people often make the mistake of viewing the dereferencing symbols as
357 proper operators, and wonder about their precedence. If they were,
358 though, you could use parentheses instead of braces. That's not the case.
359 Consider the difference below; case 0 is a short-hand version of case 1,
360 <em>not</em> case 2:</p>
361 <pre>
362 $$hashref{&quot;KEY&quot;} = &quot;VALUE&quot;; # CASE 0
363 ${$hashref}{&quot;KEY&quot;} = &quot;VALUE&quot;; # CASE 1
364 ${$hashref{&quot;KEY&quot;}} = &quot;VALUE&quot;; # CASE 2
365 ${$hashref-&gt;{&quot;KEY&quot;}} = &quot;VALUE&quot;; # CASE 3</pre>
366 <p>Case 2 is also deceptive in that you're accessing a variable
367 called %hashref, not dereferencing through $hashref to the hash
368 it's presumably referencing. That would be case 3.</p>
369 </li>
370 <li><strong><a name="item_x_3cautovivification_3e_x_3c_3c__2d_3e__3e_3e_x_3c"> &gt;&gt; </a></strong>
372 <p>Subroutine calls and lookups of individual array elements arise often
373 enough that it gets cumbersome to use method 2. As a form of
374 syntactic sugar, the examples for method 2 may be written:</p>
375 <pre>
376 $arrayref-&gt;[0] = &quot;January&quot;; # Array element
377 $hashref-&gt;{&quot;KEY&quot;} = &quot;VALUE&quot;; # Hash element
378 $coderef-&gt;(1,2,3); # Subroutine call</pre>
379 <p>The left side of the arrow can be any expression returning a reference,
380 including a previous dereference. Note that <code>$array[$x]</code> is <em>not</em> the
381 same thing as <code>$array-&gt;[$x]</code> here:</p>
382 <pre>
383 $array[$x]-&gt;{&quot;foo&quot;}-&gt;[0] = &quot;January&quot;;</pre>
384 <p>This is one of the cases we mentioned earlier in which references could
385 spring into existence when in an lvalue context. Before this
386 statement, <code>$array[$x]</code> may have been undefined. If so, it's
387 automatically defined with a hash reference so that we can look up
388 <code>{&quot;foo&quot;}</code> in it. Likewise <code>$array[$x]-&gt;{&quot;foo&quot;}</code> will automatically get
389 defined with an array reference so that we can look up <code>[0]</code> in it.
390 This process is called <em>autovivification</em>.</p>
391 <p>One more thing here. The arrow is optional <em>between</em> brackets
392 subscripts, so you can shrink the above down to</p>
393 <pre>
394 $array[$x]{&quot;foo&quot;}[0] = &quot;January&quot;;</pre>
395 <p>Which, in the degenerate case of using only ordinary arrays, gives you
396 multidimensional arrays just like C's:</p>
397 <pre>
398 $score[$x][$y][$z] += 42;</pre>
399 <p>Well, okay, not entirely like C's arrays, actually. C doesn't know how
400 to grow its arrays on demand. Perl does.</p>
401 </li>
402 <li><strong><a name="item_x_3cencapsulation_3e"></a></strong>
404 <p>If a reference happens to be a reference to an object, then there are
405 probably methods to access the things referred to, and you should probably
406 stick to those methods unless you're in the class package that defines the
407 object's methods. In other words, be nice, and don't violate the object's
408 encapsulation without a very good reason. Perl does not enforce
409 encapsulation. We are not totalitarians here. We do expect some basic
410 civility though.</p>
411 </li>
412 </ol>
413 <p>Using a string or number as a reference produces a symbolic reference,
414 as explained above. Using a reference as a number produces an
415 integer representing its storage location in memory. The only
416 useful thing to be done with this is to compare two references
417 numerically to see whether they refer to the same location.
418 </p>
419 <pre>
420 if ($ref1 == $ref2) { # cheap numeric compare of references
421 print &quot;refs 1 and 2 refer to the same thing\n&quot;;
422 }</pre>
423 <p>Using a reference as a string produces both its referent's type,
424 including any package blessing as described in <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>, as well
425 as the numeric address expressed in hex. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ref"><code>ref()</code></a> operator returns
426 just the type of thing the reference is pointing to, without the
427 address. See <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ref">ref in the perlfunc manpage</a> for details and examples of its use.
428 </p>
429 <p>The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_bless"><code>bless()</code></a> operator may be used to associate the object a reference
430 points to with a package functioning as an object class. See <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>.</p>
431 <p>A typeglob may be dereferenced the same way a reference can, because
432 the dereference syntax always indicates the type of reference desired.
433 So <code>${*foo}</code> and <code>${\$foo}</code> both indicate the same scalar variable.</p>
434 <p>Here's a trick for interpolating a subroutine call into a string:</p>
435 <pre>
436 print &quot;My sub returned @{[mysub(1,2,3)]} that time.\n&quot;;</pre>
437 <p>The way it works is that when the <code>@{...}</code> is seen in the double-quoted
438 string, it's evaluated as a block. The block creates a reference to an
439 anonymous array containing the results of the call to <code>mysub(1,2,3)</code>. So
440 the whole block returns a reference to an array, which is then
441 dereferenced by <code>@{...}</code> and stuck into the double-quoted string. This
442 chicanery is also useful for arbitrary expressions:</p>
443 <pre>
444 print &quot;That yields @{[$n + 5]} widgets\n&quot;;</pre>
446 </p>
447 <h2><a name="symbolic_references_x_reference__symbolic__x_reference__soft__x_symbolic_reference__x_soft_reference_">Symbolic references
449 </a></h2>
450 <p>We said that references spring into existence as necessary if they are
451 undefined, but we didn't say what happens if a value used as a
452 reference is already defined, but <em>isn't</em> a hard reference. If you
453 use it as a reference, it'll be treated as a symbolic
454 reference. That is, the value of the scalar is taken to be the <em>name</em>
455 of a variable, rather than a direct link to a (possibly) anonymous
456 value.</p>
457 <p>People frequently expect it to work like this. So it does.</p>
458 <pre>
459 $name = &quot;foo&quot;;
460 $$name = 1; # Sets $foo
461 ${$name} = 2; # Sets $foo
462 ${$name x 2} = 3; # Sets $foofoo
463 $name-&gt;[0] = 4; # Sets $foo[0]
464 @$name = (); # Clears @foo
465 &amp;$name(); # Calls &amp;foo() (as in Perl 4)
466 $pack = &quot;THAT&quot;;
467 ${&quot;${pack}::$name&quot;} = 5; # Sets $THAT::foo without eval</pre>
468 <p>This is powerful, and slightly dangerous, in that it's possible
469 to intend (with the utmost sincerity) to use a hard reference, and
470 accidentally use a symbolic reference instead. To protect against
471 that, you can say</p>
472 <pre>
473 use strict 'refs';</pre>
474 <p>and then only hard references will be allowed for the rest of the enclosing
475 block. An inner block may countermand that with</p>
476 <pre>
477 no strict 'refs';</pre>
478 <p>Only package variables (globals, even if localized) are visible to
479 symbolic references. Lexical variables (declared with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my())</code></a> aren't in
480 a symbol table, and thus are invisible to this mechanism. For example:</p>
481 <pre>
482 local $value = 10;
483 $ref = &quot;value&quot;;
485 my $value = 20;
486 print $$ref;
487 }</pre>
488 <p>This will still print 10, not 20. Remember that <code>local()</code> affects package
489 variables, which are all ``global'' to the package.</p>
491 </p>
492 <h2><a name="notsosymbolic_references">Not-so-symbolic references</a></h2>
493 <p>A new feature contributing to readability in perl version 5.001 is that the
494 brackets around a symbolic reference behave more like quotes, just as they
495 always have within a string. That is,</p>
496 <pre>
497 $push = &quot;pop on &quot;;
498 print &quot;${push}over&quot;;</pre>
499 <p>has always meant to print ``pop on over'', even though push is
500 a reserved word. This has been generalized to work the same outside
501 of quotes, so that</p>
502 <pre>
503 print ${push} . &quot;over&quot;;</pre>
504 <p>and even</p>
505 <pre>
506 print ${ push } . &quot;over&quot;;</pre>
507 <p>will have the same effect. (This would have been a syntax error in
508 Perl 5.000, though Perl 4 allowed it in the spaceless form.) This
509 construct is <em>not</em> considered to be a symbolic reference when you're
510 using strict refs:</p>
511 <pre>
512 use strict 'refs';
513 ${ bareword }; # Okay, means $bareword.
514 ${ &quot;bareword&quot; }; # Error, symbolic reference.</pre>
515 <p>Similarly, because of all the subscripting that is done using single
516 words, we've applied the same rule to any bareword that is used for
517 subscripting a hash. So now, instead of writing</p>
518 <pre>
519 $array{ &quot;aaa&quot; }{ &quot;bbb&quot; }{ &quot;ccc&quot; }</pre>
520 <p>you can write just</p>
521 <pre>
522 $array{ aaa }{ bbb }{ ccc }</pre>
523 <p>and not worry about whether the subscripts are reserved words. In the
524 rare event that you do wish to do something like</p>
525 <pre>
526 $array{ shift }</pre>
527 <p>you can force interpretation as a reserved word by adding anything that
528 makes it more than a bareword:</p>
529 <pre>
530 $array{ shift() }
531 $array{ +shift }
532 $array{ shift @_ }</pre>
533 <p>The <code>use warnings</code> pragma or the <strong>-w</strong> switch will warn you if it
534 interprets a reserved word as a string.
535 But it will no longer warn you about using lowercase words, because the
536 string is effectively quoted.</p>
538 </p>
539 <h2><a name="pseudohashes__using_an_array_as_a_hash_x_pseudohash__x_pseudo_hash__x_pseudohash_">Pseudo-hashes: Using an array as a hash
540 </a></h2>
541 <p><strong>WARNING</strong>: This section describes an experimental feature. Details may
542 change without notice in future versions.</p>
543 <p><strong>NOTE</strong>: The current user-visible implementation of pseudo-hashes
544 (the weird use of the first array element) is deprecated starting from
545 Perl 5.8.0 and will be removed in Perl 5.10.0, and the feature will be
546 implemented differently. Not only is the current interface rather ugly,
547 but the current implementation slows down normal array and hash use quite
548 noticeably. The 'fields' pragma interface will remain available.</p>
549 <p>Beginning with release 5.005 of Perl, you may use an array reference
550 in some contexts that would normally require a hash reference. This
551 allows you to access array elements using symbolic names, as if they
552 were fields in a structure.</p>
553 <p>For this to work, the array must contain extra information. The first
554 element of the array has to be a hash reference that maps field names
555 to array indices. Here is an example:</p>
556 <pre>
557 $struct = [{foo =&gt; 1, bar =&gt; 2}, &quot;FOO&quot;, &quot;BAR&quot;];</pre>
558 <pre>
559 $struct-&gt;{foo}; # same as $struct-&gt;[1], i.e. &quot;FOO&quot;
560 $struct-&gt;{bar}; # same as $struct-&gt;[2], i.e. &quot;BAR&quot;</pre>
561 <pre>
562 keys %$struct; # will return (&quot;foo&quot;, &quot;bar&quot;) in some order
563 values %$struct; # will return (&quot;FOO&quot;, &quot;BAR&quot;) in same some order</pre>
564 <pre>
565 while (my($k,$v) = each %$struct) {
566 print &quot;$k =&gt; $v\n&quot;;
567 }</pre>
568 <p>Perl will raise an exception if you try to access nonexistent fields.
569 To avoid inconsistencies, always use the fields::phash() function
570 provided by the <code>fields</code> pragma.</p>
571 <pre>
572 use fields;
573 $pseudohash = fields::phash(foo =&gt; &quot;FOO&quot;, bar =&gt; &quot;BAR&quot;);</pre>
574 <p>For better performance, Perl can also do the translation from field
575 names to array indices at compile time for typed object references.
576 See <a href="file://C|\msysgit\mingw\html/lib/fields.html">the fields manpage</a>.</p>
577 <p>There are two ways to check for the existence of a key in a
578 pseudo-hash. The first is to use exists(). This checks to see if the
579 given field has ever been set. It acts this way to match the behavior
580 of a regular hash. For instance:</p>
581 <pre>
582 use fields;
583 $phash = fields::phash([qw(foo bar pants)], ['FOO']);
584 $phash-&gt;{pants} = undef;</pre>
585 <pre>
586 print exists $phash-&gt;{foo}; # true, 'foo' was set in the declaration
587 print exists $phash-&gt;{bar}; # false, 'bar' has not been used.
588 print exists $phash-&gt;{pants}; # true, your 'pants' have been touched</pre>
589 <p>The second is to use <code>exists()</code> on the hash reference sitting in the
590 first array element. This checks to see if the given key is a valid
591 field in the pseudo-hash.</p>
592 <pre>
593 print exists $phash-&gt;[0]{bar}; # true, 'bar' is a valid field
594 print exists $phash-&gt;[0]{shoes};# false, 'shoes' can't be used</pre>
595 <p><code>delete()</code> on a pseudo-hash element only deletes the value corresponding
596 to the key, not the key itself. To delete the key, you'll have to
597 explicitly delete it from the first hash element.</p>
598 <pre>
599 print delete $phash-&gt;{foo}; # prints $phash-&gt;[1], &quot;FOO&quot;
600 print exists $phash-&gt;{foo}; # false
601 print exists $phash-&gt;[0]{foo}; # true, key still exists
602 print delete $phash-&gt;[0]{foo}; # now key is gone
603 print $phash-&gt;{foo}; # runtime exception</pre>
605 </p>
606 <h2><a name="function_templates_x_scope__lexical__x_closure__x_lexical__x_lexical_scope__x_subroutine__nested__x_sub__nested__x_subroutine__local__x_sub__local_">Function Templates
608 </a></h2>
609 <p>As explained above, an anonymous function with access to the lexical
610 variables visible when that function was compiled, creates a closure. It
611 retains access to those variables even though it doesn't get run until
612 later, such as in a signal handler or a Tk callback.</p>
613 <p>Using a closure as a function template allows us to generate many functions
614 that act similarly. Suppose you wanted functions named after the colors
615 that generated HTML font changes for the various colors:</p>
616 <pre>
617 print &quot;Be &quot;, red(&quot;careful&quot;), &quot;with that &quot;, green(&quot;light&quot;);</pre>
618 <p>The <code>red()</code> and <code>green()</code> functions would be similar. To create these,
619 we'll assign a closure to a typeglob of the name of the function we're
620 trying to build.</p>
621 <pre>
622 @colors = qw(red blue green yellow orange purple violet);
623 for my $name (@colors) {
624 no strict 'refs'; # allow symbol table manipulation
625 *$name = *{uc $name} = sub { &quot;&lt;FONT COLOR='$name'&gt;@_&lt;/FONT&gt;&quot; };
626 }</pre>
627 <p>Now all those different functions appear to exist independently. You can
628 call red(), RED(), blue(), BLUE(), green(), etc. This technique saves on
629 both compile time and memory use, and is less error-prone as well, since
630 syntax checks happen at compile time. It's critical that any variables in
631 the anonymous subroutine be lexicals in order to create a proper closure.
632 That's the reasons for the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my</code></a> on the loop iteration variable.</p>
633 <p>This is one of the only places where giving a prototype to a closure makes
634 much sense. If you wanted to impose scalar context on the arguments of
635 these functions (probably not a wise idea for this particular example),
636 you could have written it this way instead:</p>
637 <pre>
638 *$name = sub ($) { &quot;&lt;FONT COLOR='$name'&gt;$_[0]&lt;/FONT&gt;&quot; };</pre>
639 <p>However, since prototype checking happens at compile time, the assignment
640 above happens too late to be of much use. You could address this by
641 putting the whole loop of assignments within a BEGIN block, forcing it
642 to occur during compilation.</p>
643 <p>Access to lexicals that change over type--like those in the <code>for</code> loop
644 above--only works with closures, not general subroutines. In the general
645 case, then, named subroutines do not nest properly, although anonymous
646 ones do. Thus is because named subroutines are created (and capture any
647 outer lexicals) only once at compile time, whereas anonymous subroutines
648 get to capture each time you execute the 'sub' operator. If you are
649 accustomed to using nested subroutines in other programming languages with
650 their own private variables, you'll have to work at it a bit in Perl. The
651 intuitive coding of this type of thing incurs mysterious warnings about
652 ``will not stay shared''. For example, this won't work:</p>
653 <pre>
654 sub outer {
655 my $x = $_[0] + 35;
656 sub inner { return $x * 19 } # WRONG
657 return $x + inner();
658 }</pre>
659 <p>A work-around is the following:</p>
660 <pre>
661 sub outer {
662 my $x = $_[0] + 35;
663 local *inner = sub { return $x * 19 };
664 return $x + inner();
665 }</pre>
666 <p>Now <code>inner()</code> can only be called from within outer(), because of the
667 temporary assignments of the closure (anonymous subroutine). But when
668 it does, it has normal access to the lexical variable $x from the scope
669 of outer().</p>
670 <p>This has the interesting effect of creating a function local to another
671 function, something not normally supported in Perl.</p>
673 </p>
674 <hr />
675 <h1><a name="warning_x_reference__string_context__x_reference__use_as_hash_key_">WARNING
676 </a></h1>
677 <p>You may not (usefully) use a reference as the key to a hash. It will be
678 converted into a string:</p>
679 <pre>
680 $x{ \$a } = $a;</pre>
681 <p>If you try to dereference the key, it won't do a hard dereference, and
682 you won't accomplish what you're attempting. You might want to do something
683 more like</p>
684 <pre>
685 $r = \@a;
686 $x{ $r } = $r;</pre>
687 <p>And then at least you can use the values(), which will be
688 real refs, instead of the keys(), which won't.</p>
689 <p>The standard Tie::RefHash module provides a convenient workaround to this.</p>
691 </p>
692 <hr />
693 <h1><a name="see_also">SEE ALSO</a></h1>
694 <p>Besides the obvious documents, source code can be instructive.
695 Some pathological examples of the use of references can be found
696 in the <em>t/op/ref.t</em> regression test in the Perl source directory.</p>
697 <p>See also <a href="file://C|\msysgit\mingw\html/pod/perldsc.html">the perldsc manpage</a> and <a href="file://C|\msysgit\mingw\html/pod/perllol.html">the perllol manpage</a> for how to use references to create
698 complex data structures, and <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>, and <a href="file://C|\msysgit\mingw\html/pod/perlbot.html">the perlbot manpage</a>
699 for how to use them to create objects.</p>
700 <table border="0" width="100%" cellspacing="0" cellpadding="3">
701 <tr><td class="block" style="background-color: #cccccc" valign="middle">
702 <big><strong><span class="block">&nbsp;perlref - Perl references and nested data structures</span></strong></big>
703 </td></tr>
704 </table>
706 </body>
708 </html>