Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlref.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLREF 1"
132.TH PERLREF 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlref \- Perl references and nested data structures
135.SH "NOTE"
136.IX Header "NOTE"
137This is complete documentation about all aspects of references.
138For a shorter, tutorial introduction to just the essential features,
139see perlreftut.
140.SH "DESCRIPTION"
141.IX Header "DESCRIPTION"
142Before release 5 of Perl it was difficult to represent complex data
143structures, because all references had to be symbolic\*(--and even then
144it was difficult to refer to a variable instead of a symbol table entry.
145Perl now not only makes it easier to use symbolic references to variables,
146but also lets you have \*(L"hard\*(R" references to any piece of data or code.
147Any scalar may hold a hard reference. Because arrays and hashes contain
148scalars, you can now easily build arrays of arrays, arrays of hashes,
149hashes of arrays, arrays of hashes of functions, and so on.
150.PP
151Hard references are smart\*(--they keep track of reference counts for you,
152automatically freeing the thing referred to when its reference count goes
153to zero. (Reference counts for values in self-referential or
154cyclic data structures may not go to zero without a little help; see
155\&\*(L"Two\-Phased Garbage Collection\*(R" in perlobj for a detailed explanation.)
156If that thing happens to be an object, the object is destructed. See
157perlobj for more about objects. (In a sense, everything in Perl is an
158object, but we usually reserve the word for references to objects that
159have been officially \*(L"blessed\*(R" into a class package.)
160.PP
161Symbolic references are names of variables or other objects, just as a
162symbolic link in a Unix filesystem contains merely the name of a file.
163The \f(CW*glob\fR notation is something of a symbolic reference. (Symbolic
164references are sometimes called \*(L"soft references\*(R", but please don't call
165them that; references are confusing enough without useless synonyms.)
166.PP
167In contrast, hard references are more like hard links in a Unix file
168system: They are used to access an underlying object without concern for
169what its (other) name is. When the word \*(L"reference\*(R" is used without an
170adjective, as in the following paragraph, it is usually talking about a
171hard reference.
172.PP
173References are easy to use in Perl. There is just one overriding
174principle: Perl does no implicit referencing or dereferencing. When a
175scalar is holding a reference, it always behaves as a simple scalar. It
176doesn't magically start being an array or hash or subroutine; you have to
177tell it explicitly to do so, by dereferencing it.
178.Sh "Making References"
179.IX Subsection "Making References"
180References can be created in several ways.
181.IP "1." 4
182By using the backslash operator on a variable, subroutine, or value.
183(This works much like the & (address\-of) operator in C.)
184This typically creates \fIanother\fR reference to a variable, because
185there's already a reference to the variable in the symbol table. But
186the symbol table reference might go away, and you'll still have the
187reference that the backslash returned. Here are some examples:
188.Sp
189.Vb 5
190\& $scalarref = \e$foo;
191\& $arrayref = \e@ARGV;
192\& $hashref = \e%ENV;
193\& $coderef = \e&handler;
194\& $globref = \e*foo;
195.Ve
196.Sp
197It isn't possible to create a true reference to an \s-1IO\s0 handle (filehandle
198or dirhandle) using the backslash operator. The most you can get is a
199reference to a typeglob, which is actually a complete symbol table entry.
200But see the explanation of the \f(CW*foo{THING}\fR syntax below. However,
201you can still use type globs and globrefs as though they were \s-1IO\s0 handles.
202.IP "2." 4
203A reference to an anonymous array can be created using square
204brackets:
205.Sp
206.Vb 1
207\& $arrayref = [1, 2, ['a', 'b', 'c']];
208.Ve
209.Sp
210Here we've created a reference to an anonymous array of three elements
211whose final element is itself a reference to another anonymous array of three
212elements. (The multidimensional syntax described later can be used to
213access this. For example, after the above, \f(CW\*(C`$arrayref\->[2][1]\*(C'\fR would have
214the value \*(L"b\*(R".)
215.Sp
216Taking a reference to an enumerated list is not the same
217as using square brackets\*(--instead it's the same as creating
218a list of references!
219.Sp
220.Vb 2
221\& @list = (\e$a, \e@b, \e%c);
222\& @list = \e($a, @b, %c); # same thing!
223.Ve
224.Sp
225As a special case, \f(CW\*(C`\e(@foo)\*(C'\fR returns a list of references to the contents
226of \f(CW@foo\fR, not a reference to \f(CW@foo\fR itself. Likewise for \f(CW%foo\fR,
227except that the key references are to copies (since the keys are just
228strings rather than full-fledged scalars).
229.IP "3." 4
230A reference to an anonymous hash can be created using curly
231brackets:
232.Sp
233.Vb 4
234\& $hashref = {
235\& 'Adam' => 'Eve',
236\& 'Clyde' => 'Bonnie',
237\& };
238.Ve
239.Sp
240Anonymous hash and array composers like these can be intermixed freely to
241produce as complicated a structure as you want. The multidimensional
242syntax described below works for these too. The values above are
243literals, but variables and expressions would work just as well, because
244assignment operators in Perl (even within \fIlocal()\fR or \fImy()\fR) are executable
245statements, not compile-time declarations.
246.Sp
247Because curly brackets (braces) are used for several other things
248including BLOCKs, you may occasionally have to disambiguate braces at the
249beginning of a statement by putting a \f(CW\*(C`+\*(C'\fR or a \f(CW\*(C`return\*(C'\fR in front so
250that Perl realizes the opening brace isn't starting a \s-1BLOCK\s0. The economy and
251mnemonic value of using curlies is deemed worth this occasional extra
252hassle.
253.Sp
254For example, if you wanted a function to make a new hash and return a
255reference to it, you have these options:
256.Sp
257.Vb 3
258\& sub hashem { { @_ } } # silently wrong
259\& sub hashem { +{ @_ } } # ok
260\& sub hashem { return { @_ } } # ok
261.Ve
262.Sp
263On the other hand, if you want the other meaning, you can do this:
264.Sp
265.Vb 3
266\& sub showem { { @_ } } # ambiguous (currently ok, but may change)
267\& sub showem { {; @_ } } # ok
268\& sub showem { { return @_ } } # ok
269.Ve
270.Sp
271The leading \f(CW\*(C`+{\*(C'\fR and \f(CW\*(C`{;\*(C'\fR always serve to disambiguate
272the expression to mean either the \s-1HASH\s0 reference, or the \s-1BLOCK\s0.
273.IP "4." 4
274A reference to an anonymous subroutine can be created by using
275\&\f(CW\*(C`sub\*(C'\fR without a subname:
276.Sp
277.Vb 1
278\& $coderef = sub { print "Boink!\en" };
279.Ve
280.Sp
281Note the semicolon. Except for the code
282inside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much a
283declaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR. (However, no
284matter how many times you execute that particular line (unless you're in an
285\&\f(CW\*(C`eval("...")\*(C'\fR), \f(CW$coderef\fR will still have a reference to the \fIsame\fR
286anonymous subroutine.)
287.Sp
288Anonymous subroutines act as closures with respect to \fImy()\fR variables,
289that is, variables lexically visible within the current scope. Closure
290is a notion out of the Lisp world that says if you define an anonymous
291function in a particular lexical context, it pretends to run in that
292context even when it's called outside the context.
293.Sp
294In human terms, it's a funny way of passing arguments to a subroutine when
295you define it as well as when you call it. It's useful for setting up
296little bits of code to run later, such as callbacks. You can even
297do object-oriented stuff with it, though Perl already provides a different
298mechanism to do that\*(--see perlobj.
299.Sp
300You might also think of closure as a way to write a subroutine
301template without using \fIeval()\fR. Here's a small example of how
302closures work:
303.Sp
304.Vb 6
305\& sub newprint {
306\& my $x = shift;
307\& return sub { my $y = shift; print "$x, $y!\en"; };
308\& }
309\& $h = newprint("Howdy");
310\& $g = newprint("Greetings");
311.Ve
312.Sp
313.Vb 1
314\& # Time passes...
315.Ve
316.Sp
317.Vb 2
318\& &$h("world");
319\& &$g("earthlings");
320.Ve
321.Sp
322This prints
323.Sp
324.Vb 2
325\& Howdy, world!
326\& Greetings, earthlings!
327.Ve
328.Sp
329Note particularly that \f(CW$x\fR continues to refer to the value passed
330into \fInewprint()\fR \fIdespite\fR \*(L"my \f(CW$x\fR\*(R" having gone out of scope by the
331time the anonymous subroutine runs. That's what a closure is all
332about.
333.Sp
334This applies only to lexical variables, by the way. Dynamic variables
335continue to work as they have always worked. Closure is not something
336that most Perl programmers need trouble themselves about to begin with.
337.IP "5." 4
338References are often returned by special subroutines called constructors.
339Perl objects are just references to a special type of object that happens to know
340which package it's associated with. Constructors are just special
341subroutines that know how to create that association. They do so by
342starting with an ordinary reference, and it remains an ordinary reference
343even while it's also being an object. Constructors are often
344named \fInew()\fR and called indirectly:
345.Sp
346.Vb 1
347\& $objref = new Doggie (Tail => 'short', Ears => 'long');
348.Ve
349.Sp
350But don't have to be:
351.Sp
352.Vb 1
353\& $objref = Doggie->new(Tail => 'short', Ears => 'long');
354.Ve
355.Sp
356.Vb 2
357\& use Term::Cap;
358\& $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });
359.Ve
360.Sp
361.Vb 4
362\& use Tk;
363\& $main = MainWindow->new();
364\& $menubar = $main->Frame(-relief => "raised",
365\& -borderwidth => 2)
366.Ve
367.IP "6." 4
368References of the appropriate type can spring into existence if you
369dereference them in a context that assumes they exist. Because we haven't
370talked about dereferencing yet, we can't show you any examples yet.
371.IP "7." 4
372A reference can be created by using a special syntax, lovingly known as
373the *foo{\s-1THING\s0} syntax. *foo{\s-1THING\s0} returns a reference to the \s-1THING\s0
374slot in *foo (which is the symbol table entry which holds everything
375known as foo).
376.Sp
377.Vb 6
378\& $scalarref = *foo{SCALAR};
379\& $arrayref = *ARGV{ARRAY};
380\& $hashref = *ENV{HASH};
381\& $coderef = *handler{CODE};
382\& $ioref = *STDIN{IO};
383\& $globref = *foo{GLOB};
384.Ve
385.Sp
386All of these are self-explanatory except for \f(CW*foo{IO}\fR. It returns
387the \s-1IO\s0 handle, used for file handles (\*(L"open\*(R" in perlfunc), sockets
388(\*(L"socket\*(R" in perlfunc and \*(L"socketpair\*(R" in perlfunc), and directory
389handles (\*(L"opendir\*(R" in perlfunc). For compatibility with previous
390versions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though it
391is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn
392of its use.
393.Sp
394\&\f(CW*foo{THING}\fR returns undef if that particular \s-1THING\s0 hasn't been used yet,
395except in the case of scalars. \f(CW*foo{SCALAR}\fR returns a reference to an
396anonymous scalar if \f(CW$foo\fR hasn't been used yet. This might change in a
397future release.
398.Sp
399\&\f(CW*foo{IO}\fR is an alternative to the \f(CW*HANDLE\fR mechanism given in
400\&\*(L"Typeglobs and Filehandles\*(R" in perldata for passing filehandles
401into or out of subroutines, or storing into larger data structures.
402Its disadvantage is that it won't create a new filehandle for you.
403Its advantage is that you have less risk of clobbering more than
404you want to with a typeglob assignment. (It still conflates file
405and directory handles, though.) However, if you assign the incoming
406value to a scalar instead of a typeglob as we do in the examples
407below, there's no risk of that happening.
408.Sp
409.Vb 2
410\& splutter(*STDOUT); # pass the whole glob
411\& splutter(*STDOUT{IO}); # pass both file and dir handles
412.Ve
413.Sp
414.Vb 4
415\& sub splutter {
416\& my $fh = shift;
417\& print $fh "her um well a hmmm\en";
418\& }
419.Ve
420.Sp
421.Vb 2
422\& $rec = get_rec(*STDIN); # pass the whole glob
423\& $rec = get_rec(*STDIN{IO}); # pass both file and dir handles
424.Ve
425.Sp
426.Vb 4
427\& sub get_rec {
428\& my $fh = shift;
429\& return scalar <$fh>;
430\& }
431.Ve
432.Sh "Using References"
433.IX Subsection "Using References"
434That's it for creating references. By now you're probably dying to
435know how to use references to get back to your long-lost data. There
436are several basic methods.
437.IP "1." 4
438Anywhere you'd put an identifier (or chain of identifiers) as part
439of a variable or subroutine name, you can replace the identifier with
440a simple scalar variable containing a reference of the correct type:
441.Sp
442.Vb 6
443\& $bar = $$scalarref;
444\& push(@$arrayref, $filename);
445\& $$arrayref[0] = "January";
446\& $$hashref{"KEY"} = "VALUE";
447\& &$coderef(1,2,3);
448\& print $globref "output\en";
449.Ve
450.Sp
451It's important to understand that we are specifically \fInot\fR dereferencing
452\&\f(CW$arrayref[0]\fR or \f(CW$hashref{"KEY"}\fR there. The dereference of the
453scalar variable happens \fIbefore\fR it does any key lookups. Anything more
454complicated than a simple scalar variable must use methods 2 or 3 below.
455However, a \*(L"simple scalar\*(R" includes an identifier that itself uses method
4561 recursively. Therefore, the following prints \*(L"howdy\*(R".
457.Sp
458.Vb 2
459\& $refrefref = \e\e\e"howdy";
460\& print $$$$refrefref;
461.Ve
462.IP "2." 4
463Anywhere you'd put an identifier (or chain of identifiers) as part of a
464variable or subroutine name, you can replace the identifier with a
465\&\s-1BLOCK\s0 returning a reference of the correct type. In other words, the
466previous examples could be written like this:
467.Sp
468.Vb 6
469\& $bar = ${$scalarref};
470\& push(@{$arrayref}, $filename);
471\& ${$arrayref}[0] = "January";
472\& ${$hashref}{"KEY"} = "VALUE";
473\& &{$coderef}(1,2,3);
474\& $globref->print("output\en"); # iff IO::Handle is loaded
475.Ve
476.Sp
477Admittedly, it's a little silly to use the curlies in this case, but
478the \s-1BLOCK\s0 can contain any arbitrary expression, in particular,
479subscripted expressions:
480.Sp
481.Vb 1
482\& &{ $dispatch{$index} }(1,2,3); # call correct routine
483.Ve
484.Sp
485Because of being able to omit the curlies for the simple case of \f(CW$$x\fR,
486people often make the mistake of viewing the dereferencing symbols as
487proper operators, and wonder about their precedence. If they were,
488though, you could use parentheses instead of braces. That's not the case.
489Consider the difference below; case 0 is a short-hand version of case 1,
490\&\fInot\fR case 2:
491.Sp
492.Vb 4
493\& $$hashref{"KEY"} = "VALUE"; # CASE 0
494\& ${$hashref}{"KEY"} = "VALUE"; # CASE 1
495\& ${$hashref{"KEY"}} = "VALUE"; # CASE 2
496\& ${$hashref->{"KEY"}} = "VALUE"; # CASE 3
497.Ve
498.Sp
499Case 2 is also deceptive in that you're accessing a variable
500called \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hash
501it's presumably referencing. That would be case 3.
502.IP "3." 4
503Subroutine calls and lookups of individual array elements arise often
504enough that it gets cumbersome to use method 2. As a form of
505syntactic sugar, the examples for method 2 may be written:
506.Sp
507.Vb 3
508\& $arrayref->[0] = "January"; # Array element
509\& $hashref->{"KEY"} = "VALUE"; # Hash element
510\& $coderef->(1,2,3); # Subroutine call
511.Ve
512.Sp
513The left side of the arrow can be any expression returning a reference,
514including a previous dereference. Note that \f(CW$array[$x]\fR is \fInot\fR the
515same thing as \f(CW\*(C`$array\->[$x]\*(C'\fR here:
516.Sp
517.Vb 1
518\& $array[$x]->{"foo"}->[0] = "January";
519.Ve
520.Sp
521This is one of the cases we mentioned earlier in which references could
522spring into existence when in an lvalue context. Before this
523statement, \f(CW$array[$x]\fR may have been undefined. If so, it's
524automatically defined with a hash reference so that we can look up
525\&\f(CW\*(C`{"foo"}\*(C'\fR in it. Likewise \f(CW\*(C`$array[$x]\->{"foo"}\*(C'\fR will automatically get
526defined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it.
527This process is called \fIautovivification\fR.
528.Sp
529One more thing here. The arrow is optional \fIbetween\fR brackets
530subscripts, so you can shrink the above down to
531.Sp
532.Vb 1
533\& $array[$x]{"foo"}[0] = "January";
534.Ve
535.Sp
536Which, in the degenerate case of using only ordinary arrays, gives you
537multidimensional arrays just like C's:
538.Sp
539.Vb 1
540\& $score[$x][$y][$z] += 42;
541.Ve
542.Sp
543Well, okay, not entirely like C's arrays, actually. C doesn't know how
544to grow its arrays on demand. Perl does.
545.IP "4." 4
546If a reference happens to be a reference to an object, then there are
547probably methods to access the things referred to, and you should probably
548stick to those methods unless you're in the class package that defines the
549object's methods. In other words, be nice, and don't violate the object's
550encapsulation without a very good reason. Perl does not enforce
551encapsulation. We are not totalitarians here. We do expect some basic
552civility though.
553.PP
554Using a string or number as a reference produces a symbolic reference,
555as explained above. Using a reference as a number produces an
556integer representing its storage location in memory. The only
557useful thing to be done with this is to compare two references
558numerically to see whether they refer to the same location.
559.PP
560.Vb 3
561\& if ($ref1 == $ref2) { # cheap numeric compare of references
562\& print "refs 1 and 2 refer to the same thing\en";
563\& }
564.Ve
565.PP
566Using a reference as a string produces both its referent's type,
567including any package blessing as described in perlobj, as well
568as the numeric address expressed in hex. The \fIref()\fR operator returns
569just the type of thing the reference is pointing to, without the
570address. See \*(L"ref\*(R" in perlfunc for details and examples of its use.
571.PP
572The \fIbless()\fR operator may be used to associate the object a reference
573points to with a package functioning as an object class. See perlobj.
574.PP
575A typeglob may be dereferenced the same way a reference can, because
576the dereference syntax always indicates the type of reference desired.
577So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable.
578.PP
579Here's a trick for interpolating a subroutine call into a string:
580.PP
581.Vb 1
582\& print "My sub returned @{[mysub(1,2,3)]} that time.\en";
583.Ve
584.PP
585The way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quoted
586string, it's evaluated as a block. The block creates a reference to an
587anonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR. So
588the whole block returns a reference to an array, which is then
589dereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. This
590chicanery is also useful for arbitrary expressions:
591.PP
592.Vb 1
593\& print "That yields @{[$n + 5]} widgets\en";
594.Ve
595.Sh "Symbolic references"
596.IX Subsection "Symbolic references"
597We said that references spring into existence as necessary if they are
598undefined, but we didn't say what happens if a value used as a
599reference is already defined, but \fIisn't\fR a hard reference. If you
600use it as a reference, it'll be treated as a symbolic
601reference. That is, the value of the scalar is taken to be the \fIname\fR
602of a variable, rather than a direct link to a (possibly) anonymous
603value.
604.PP
605People frequently expect it to work like this. So it does.
606.PP
607.Vb 9
608\& $name = "foo";
609\& $$name = 1; # Sets $foo
610\& ${$name} = 2; # Sets $foo
611\& ${$name x 2} = 3; # Sets $foofoo
612\& $name->[0] = 4; # Sets $foo[0]
613\& @$name = (); # Clears @foo
614\& &$name(); # Calls &foo() (as in Perl 4)
615\& $pack = "THAT";
616\& ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval
617.Ve
618.PP
619This is powerful, and slightly dangerous, in that it's possible
620to intend (with the utmost sincerity) to use a hard reference, and
621accidentally use a symbolic reference instead. To protect against
622that, you can say
623.PP
624.Vb 1
625\& use strict 'refs';
626.Ve
627.PP
628and then only hard references will be allowed for the rest of the enclosing
629block. An inner block may countermand that with
630.PP
631.Vb 1
632\& no strict 'refs';
633.Ve
634.PP
635Only package variables (globals, even if localized) are visible to
636symbolic references. Lexical variables (declared with \fImy()\fR) aren't in
637a symbol table, and thus are invisible to this mechanism. For example:
638.PP
639.Vb 6
640\& local $value = 10;
641\& $ref = "value";
642\& {
643\& my $value = 20;
644\& print $$ref;
645\& }
646.Ve
647.PP
648This will still print 10, not 20. Remember that \fIlocal()\fR affects package
649variables, which are all \*(L"global\*(R" to the package.
650.Sh "Not-so-symbolic references"
651.IX Subsection "Not-so-symbolic references"
652A new feature contributing to readability in perl version 5.001 is that the
653brackets around a symbolic reference behave more like quotes, just as they
654always have within a string. That is,
655.PP
656.Vb 2
657\& $push = "pop on ";
658\& print "${push}over";
659.Ve
660.PP
661has always meant to print \*(L"pop on over\*(R", even though push is
662a reserved word. This has been generalized to work the same outside
663of quotes, so that
664.PP
665.Vb 1
666\& print ${push} . "over";
667.Ve
668.PP
669and even
670.PP
671.Vb 1
672\& print ${ push } . "over";
673.Ve
674.PP
675will have the same effect. (This would have been a syntax error in
676Perl 5.000, though Perl 4 allowed it in the spaceless form.) This
677construct is \fInot\fR considered to be a symbolic reference when you're
678using strict refs:
679.PP
680.Vb 3
681\& use strict 'refs';
682\& ${ bareword }; # Okay, means $bareword.
683\& ${ "bareword" }; # Error, symbolic reference.
684.Ve
685.PP
686Similarly, because of all the subscripting that is done using single
687words, we've applied the same rule to any bareword that is used for
688subscripting a hash. So now, instead of writing
689.PP
690.Vb 1
691\& $array{ "aaa" }{ "bbb" }{ "ccc" }
692.Ve
693.PP
694you can write just
695.PP
696.Vb 1
697\& $array{ aaa }{ bbb }{ ccc }
698.Ve
699.PP
700and not worry about whether the subscripts are reserved words. In the
701rare event that you do wish to do something like
702.PP
703.Vb 1
704\& $array{ shift }
705.Ve
706.PP
707you can force interpretation as a reserved word by adding anything that
708makes it more than a bareword:
709.PP
710.Vb 3
711\& $array{ shift() }
712\& $array{ +shift }
713\& $array{ shift @_ }
714.Ve
715.PP
716The \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch will warn you if it
717interprets a reserved word as a string.
718But it will no longer warn you about using lowercase words, because the
719string is effectively quoted.
720.Sh "Pseudo\-hashes: Using an array as a hash"
721.IX Subsection "Pseudo-hashes: Using an array as a hash"
722\&\fB\s-1WARNING\s0\fR: This section describes an experimental feature. Details may
723change without notice in future versions.
724.PP
725\&\fB\s-1NOTE\s0\fR: The current user-visible implementation of pseudo-hashes
726(the weird use of the first array element) is deprecated starting from
727Perl 5.8.0 and will be removed in Perl 5.10.0, and the feature will be
728implemented differently. Not only is the current interface rather ugly,
729but the current implementation slows down normal array and hash use quite
730noticeably. The 'fields' pragma interface will remain available.
731.PP
732Beginning with release 5.005 of Perl, you may use an array reference
733in some contexts that would normally require a hash reference. This
734allows you to access array elements using symbolic names, as if they
735were fields in a structure.
736.PP
737For this to work, the array must contain extra information. The first
738element of the array has to be a hash reference that maps field names
739to array indices. Here is an example:
740.PP
741.Vb 1
742\& $struct = [{foo => 1, bar => 2}, "FOO", "BAR"];
743.Ve
744.PP
745.Vb 2
746\& $struct->{foo}; # same as $struct->[1], i.e. "FOO"
747\& $struct->{bar}; # same as $struct->[2], i.e. "BAR"
748.Ve
749.PP
750.Vb 2
751\& keys %$struct; # will return ("foo", "bar") in some order
752\& values %$struct; # will return ("FOO", "BAR") in same some order
753.Ve
754.PP
755.Vb 3
756\& while (my($k,$v) = each %$struct) {
757\& print "$k => $v\en";
758\& }
759.Ve
760.PP
761Perl will raise an exception if you try to access nonexistent fields.
762To avoid inconsistencies, always use the \fIfields::phash()\fR function
763provided by the \f(CW\*(C`fields\*(C'\fR pragma.
764.PP
765.Vb 2
766\& use fields;
767\& $pseudohash = fields::phash(foo => "FOO", bar => "BAR");
768.Ve
769.PP
770For better performance, Perl can also do the translation from field
771names to array indices at compile time for typed object references.
772See fields.
773.PP
774There are two ways to check for the existence of a key in a
775pseudo\-hash. The first is to use \fIexists()\fR. This checks to see if the
776given field has ever been set. It acts this way to match the behavior
777of a regular hash. For instance:
778.PP
779.Vb 3
780\& use fields;
781\& $phash = fields::phash([qw(foo bar pants)], ['FOO']);
782\& $phash->{pants} = undef;
783.Ve
784.PP
785.Vb 3
786\& print exists $phash->{foo}; # true, 'foo' was set in the declaration
787\& print exists $phash->{bar}; # false, 'bar' has not been used.
788\& print exists $phash->{pants}; # true, your 'pants' have been touched
789.Ve
790.PP
791The second is to use \fIexists()\fR on the hash reference sitting in the
792first array element. This checks to see if the given key is a valid
793field in the pseudo\-hash.
794.PP
795.Vb 2
796\& print exists $phash->[0]{bar}; # true, 'bar' is a valid field
797\& print exists $phash->[0]{shoes};# false, 'shoes' can't be used
798.Ve
799.PP
800\&\fIdelete()\fR on a pseudo-hash element only deletes the value corresponding
801to the key, not the key itself. To delete the key, you'll have to
802explicitly delete it from the first hash element.
803.PP
804.Vb 5
805\& print delete $phash->{foo}; # prints $phash->[1], "FOO"
806\& print exists $phash->{foo}; # false
807\& print exists $phash->[0]{foo}; # true, key still exists
808\& print delete $phash->[0]{foo}; # now key is gone
809\& print $phash->{foo}; # runtime exception
810.Ve
811.Sh "Function Templates"
812.IX Subsection "Function Templates"
813As explained above, a closure is an anonymous function with access to the
814lexical variables visible when that function was compiled. It retains
815access to those variables even though it doesn't get run until later,
816such as in a signal handler or a Tk callback.
817.PP
818Using a closure as a function template allows us to generate many functions
819that act similarly. Suppose you wanted functions named after the colors
820that generated \s-1HTML\s0 font changes for the various colors:
821.PP
822.Vb 1
823\& print "Be ", red("careful"), "with that ", green("light");
824.Ve
825.PP
826The \fIred()\fR and \fIgreen()\fR functions would be similar. To create these,
827we'll assign a closure to a typeglob of the name of the function we're
828trying to build.
829.PP
830.Vb 5
831\& @colors = qw(red blue green yellow orange purple violet);
832\& for my $name (@colors) {
833\& no strict 'refs'; # allow symbol table manipulation
834\& *$name = *{uc $name} = sub { "<FONT COLOR='$name'>@_</FONT>" };
835\& }
836.Ve
837.PP
838Now all those different functions appear to exist independently. You can
839call \fIred()\fR, \s-1\fIRED\s0()\fR, \fIblue()\fR, \s-1\fIBLUE\s0()\fR, \fIgreen()\fR, etc. This technique saves on
840both compile time and memory use, and is less error-prone as well, since
841syntax checks happen at compile time. It's critical that any variables in
842the anonymous subroutine be lexicals in order to create a proper closure.
843That's the reasons for the \f(CW\*(C`my\*(C'\fR on the loop iteration variable.
844.PP
845This is one of the only places where giving a prototype to a closure makes
846much sense. If you wanted to impose scalar context on the arguments of
847these functions (probably not a wise idea for this particular example),
848you could have written it this way instead:
849.PP
850.Vb 1
851\& *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" };
852.Ve
853.PP
854However, since prototype checking happens at compile time, the assignment
855above happens too late to be of much use. You could address this by
856putting the whole loop of assignments within a \s-1BEGIN\s0 block, forcing it
857to occur during compilation.
858.PP
859Access to lexicals that change over type\*(--like those in the \f(CW\*(C`for\*(C'\fR loop
860above\*(--only works with closures, not general subroutines. In the general
861case, then, named subroutines do not nest properly, although anonymous
862ones do. If you are accustomed to using nested subroutines in other
863programming languages with their own private variables, you'll have to
864work at it a bit in Perl. The intuitive coding of this type of thing
865incurs mysterious warnings about ``will not stay shared''. For example,
866this won't work:
867.PP
868.Vb 5
869\& sub outer {
870\& my $x = $_[0] + 35;
871\& sub inner { return $x * 19 } # WRONG
872\& return $x + inner();
873\& }
874.Ve
875.PP
876A work-around is the following:
877.PP
878.Vb 5
879\& sub outer {
880\& my $x = $_[0] + 35;
881\& local *inner = sub { return $x * 19 };
882\& return $x + inner();
883\& }
884.Ve
885.PP
886Now \fIinner()\fR can only be called from within \fIouter()\fR, because of the
887temporary assignments of the closure (anonymous subroutine). But when
888it does, it has normal access to the lexical variable \f(CW$x\fR from the scope
889of \fIouter()\fR.
890.PP
891This has the interesting effect of creating a function local to another
892function, something not normally supported in Perl.
893.SH "WARNING"
894.IX Header "WARNING"
895You may not (usefully) use a reference as the key to a hash. It will be
896converted into a string:
897.PP
898.Vb 1
899\& $x{ \e$a } = $a;
900.Ve
901.PP
902If you try to dereference the key, it won't do a hard dereference, and
903you won't accomplish what you're attempting. You might want to do something
904more like
905.PP
906.Vb 2
907\& $r = \e@a;
908\& $x{ $r } = $r;
909.Ve
910.PP
911And then at least you can use the \fIvalues()\fR, which will be
912real refs, instead of the \fIkeys()\fR, which won't.
913.PP
914The standard Tie::RefHash module provides a convenient workaround to this.
915.SH "SEE ALSO"
916.IX Header "SEE ALSO"
917Besides the obvious documents, source code can be instructive.
918Some pathological examples of the use of references can be found
919in the \fIt/op/ref.t\fR regression test in the Perl source directory.
920.PP
921See also perldsc and perllol for how to use references to create
922complex data structures, and perltoot, perlobj, and perlbot
923for how to use them to create objects.