Commit | Line | Data |
---|---|---|
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" | |
134 | perlref \- Perl references and nested data structures | |
135 | .SH "NOTE" | |
136 | .IX Header "NOTE" | |
137 | This is complete documentation about all aspects of references. | |
138 | For a shorter, tutorial introduction to just the essential features, | |
139 | see perlreftut. | |
140 | .SH "DESCRIPTION" | |
141 | .IX Header "DESCRIPTION" | |
142 | Before release 5 of Perl it was difficult to represent complex data | |
143 | structures, because all references had to be symbolic\*(--and even then | |
144 | it was difficult to refer to a variable instead of a symbol table entry. | |
145 | Perl now not only makes it easier to use symbolic references to variables, | |
146 | but also lets you have \*(L"hard\*(R" references to any piece of data or code. | |
147 | Any scalar may hold a hard reference. Because arrays and hashes contain | |
148 | scalars, you can now easily build arrays of arrays, arrays of hashes, | |
149 | hashes of arrays, arrays of hashes of functions, and so on. | |
150 | .PP | |
151 | Hard references are smart\*(--they keep track of reference counts for you, | |
152 | automatically freeing the thing referred to when its reference count goes | |
153 | to zero. (Reference counts for values in self-referential or | |
154 | cyclic 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.) | |
156 | If that thing happens to be an object, the object is destructed. See | |
157 | perlobj for more about objects. (In a sense, everything in Perl is an | |
158 | object, but we usually reserve the word for references to objects that | |
159 | have been officially \*(L"blessed\*(R" into a class package.) | |
160 | .PP | |
161 | Symbolic references are names of variables or other objects, just as a | |
162 | symbolic link in a Unix filesystem contains merely the name of a file. | |
163 | The \f(CW*glob\fR notation is something of a symbolic reference. (Symbolic | |
164 | references are sometimes called \*(L"soft references\*(R", but please don't call | |
165 | them that; references are confusing enough without useless synonyms.) | |
166 | .PP | |
167 | In contrast, hard references are more like hard links in a Unix file | |
168 | system: They are used to access an underlying object without concern for | |
169 | what its (other) name is. When the word \*(L"reference\*(R" is used without an | |
170 | adjective, as in the following paragraph, it is usually talking about a | |
171 | hard reference. | |
172 | .PP | |
173 | References are easy to use in Perl. There is just one overriding | |
174 | principle: Perl does no implicit referencing or dereferencing. When a | |
175 | scalar is holding a reference, it always behaves as a simple scalar. It | |
176 | doesn't magically start being an array or hash or subroutine; you have to | |
177 | tell it explicitly to do so, by dereferencing it. | |
178 | .Sh "Making References" | |
179 | .IX Subsection "Making References" | |
180 | References can be created in several ways. | |
181 | .IP "1." 4 | |
182 | By using the backslash operator on a variable, subroutine, or value. | |
183 | (This works much like the & (address\-of) operator in C.) | |
184 | This typically creates \fIanother\fR reference to a variable, because | |
185 | there's already a reference to the variable in the symbol table. But | |
186 | the symbol table reference might go away, and you'll still have the | |
187 | reference 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 | |
197 | It isn't possible to create a true reference to an \s-1IO\s0 handle (filehandle | |
198 | or dirhandle) using the backslash operator. The most you can get is a | |
199 | reference to a typeglob, which is actually a complete symbol table entry. | |
200 | But see the explanation of the \f(CW*foo{THING}\fR syntax below. However, | |
201 | you can still use type globs and globrefs as though they were \s-1IO\s0 handles. | |
202 | .IP "2." 4 | |
203 | A reference to an anonymous array can be created using square | |
204 | brackets: | |
205 | .Sp | |
206 | .Vb 1 | |
207 | \& $arrayref = [1, 2, ['a', 'b', 'c']]; | |
208 | .Ve | |
209 | .Sp | |
210 | Here we've created a reference to an anonymous array of three elements | |
211 | whose final element is itself a reference to another anonymous array of three | |
212 | elements. (The multidimensional syntax described later can be used to | |
213 | access this. For example, after the above, \f(CW\*(C`$arrayref\->[2][1]\*(C'\fR would have | |
214 | the value \*(L"b\*(R".) | |
215 | .Sp | |
216 | Taking a reference to an enumerated list is not the same | |
217 | as using square brackets\*(--instead it's the same as creating | |
218 | a 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 | |
225 | As a special case, \f(CW\*(C`\e(@foo)\*(C'\fR returns a list of references to the contents | |
226 | of \f(CW@foo\fR, not a reference to \f(CW@foo\fR itself. Likewise for \f(CW%foo\fR, | |
227 | except that the key references are to copies (since the keys are just | |
228 | strings rather than full-fledged scalars). | |
229 | .IP "3." 4 | |
230 | A reference to an anonymous hash can be created using curly | |
231 | brackets: | |
232 | .Sp | |
233 | .Vb 4 | |
234 | \& $hashref = { | |
235 | \& 'Adam' => 'Eve', | |
236 | \& 'Clyde' => 'Bonnie', | |
237 | \& }; | |
238 | .Ve | |
239 | .Sp | |
240 | Anonymous hash and array composers like these can be intermixed freely to | |
241 | produce as complicated a structure as you want. The multidimensional | |
242 | syntax described below works for these too. The values above are | |
243 | literals, but variables and expressions would work just as well, because | |
244 | assignment operators in Perl (even within \fIlocal()\fR or \fImy()\fR) are executable | |
245 | statements, not compile-time declarations. | |
246 | .Sp | |
247 | Because curly brackets (braces) are used for several other things | |
248 | including BLOCKs, you may occasionally have to disambiguate braces at the | |
249 | beginning of a statement by putting a \f(CW\*(C`+\*(C'\fR or a \f(CW\*(C`return\*(C'\fR in front so | |
250 | that Perl realizes the opening brace isn't starting a \s-1BLOCK\s0. The economy and | |
251 | mnemonic value of using curlies is deemed worth this occasional extra | |
252 | hassle. | |
253 | .Sp | |
254 | For example, if you wanted a function to make a new hash and return a | |
255 | reference 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 | |
263 | On 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 | |
271 | The leading \f(CW\*(C`+{\*(C'\fR and \f(CW\*(C`{;\*(C'\fR always serve to disambiguate | |
272 | the expression to mean either the \s-1HASH\s0 reference, or the \s-1BLOCK\s0. | |
273 | .IP "4." 4 | |
274 | A 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 | |
281 | Note the semicolon. Except for the code | |
282 | inside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much a | |
283 | declaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR. (However, no | |
284 | matter 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 | |
286 | anonymous subroutine.) | |
287 | .Sp | |
288 | Anonymous subroutines act as closures with respect to \fImy()\fR variables, | |
289 | that is, variables lexically visible within the current scope. Closure | |
290 | is a notion out of the Lisp world that says if you define an anonymous | |
291 | function in a particular lexical context, it pretends to run in that | |
292 | context even when it's called outside the context. | |
293 | .Sp | |
294 | In human terms, it's a funny way of passing arguments to a subroutine when | |
295 | you define it as well as when you call it. It's useful for setting up | |
296 | little bits of code to run later, such as callbacks. You can even | |
297 | do object-oriented stuff with it, though Perl already provides a different | |
298 | mechanism to do that\*(--see perlobj. | |
299 | .Sp | |
300 | You might also think of closure as a way to write a subroutine | |
301 | template without using \fIeval()\fR. Here's a small example of how | |
302 | closures 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 | |
322 | This prints | |
323 | .Sp | |
324 | .Vb 2 | |
325 | \& Howdy, world! | |
326 | \& Greetings, earthlings! | |
327 | .Ve | |
328 | .Sp | |
329 | Note particularly that \f(CW$x\fR continues to refer to the value passed | |
330 | into \fInewprint()\fR \fIdespite\fR \*(L"my \f(CW$x\fR\*(R" having gone out of scope by the | |
331 | time the anonymous subroutine runs. That's what a closure is all | |
332 | about. | |
333 | .Sp | |
334 | This applies only to lexical variables, by the way. Dynamic variables | |
335 | continue to work as they have always worked. Closure is not something | |
336 | that most Perl programmers need trouble themselves about to begin with. | |
337 | .IP "5." 4 | |
338 | References are often returned by special subroutines called constructors. | |
339 | Perl objects are just references to a special type of object that happens to know | |
340 | which package it's associated with. Constructors are just special | |
341 | subroutines that know how to create that association. They do so by | |
342 | starting with an ordinary reference, and it remains an ordinary reference | |
343 | even while it's also being an object. Constructors are often | |
344 | named \fInew()\fR and called indirectly: | |
345 | .Sp | |
346 | .Vb 1 | |
347 | \& $objref = new Doggie (Tail => 'short', Ears => 'long'); | |
348 | .Ve | |
349 | .Sp | |
350 | But 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 | |
368 | References of the appropriate type can spring into existence if you | |
369 | dereference them in a context that assumes they exist. Because we haven't | |
370 | talked about dereferencing yet, we can't show you any examples yet. | |
371 | .IP "7." 4 | |
372 | A reference can be created by using a special syntax, lovingly known as | |
373 | the *foo{\s-1THING\s0} syntax. *foo{\s-1THING\s0} returns a reference to the \s-1THING\s0 | |
374 | slot in *foo (which is the symbol table entry which holds everything | |
375 | known 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 | |
386 | All of these are self-explanatory except for \f(CW*foo{IO}\fR. It returns | |
387 | the \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 | |
389 | handles (\*(L"opendir\*(R" in perlfunc). For compatibility with previous | |
390 | versions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though it | |
391 | is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn | |
392 | of its use. | |
393 | .Sp | |
394 | \&\f(CW*foo{THING}\fR returns undef if that particular \s-1THING\s0 hasn't been used yet, | |
395 | except in the case of scalars. \f(CW*foo{SCALAR}\fR returns a reference to an | |
396 | anonymous scalar if \f(CW$foo\fR hasn't been used yet. This might change in a | |
397 | future 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 | |
401 | into or out of subroutines, or storing into larger data structures. | |
402 | Its disadvantage is that it won't create a new filehandle for you. | |
403 | Its advantage is that you have less risk of clobbering more than | |
404 | you want to with a typeglob assignment. (It still conflates file | |
405 | and directory handles, though.) However, if you assign the incoming | |
406 | value to a scalar instead of a typeglob as we do in the examples | |
407 | below, 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" | |
434 | That's it for creating references. By now you're probably dying to | |
435 | know how to use references to get back to your long-lost data. There | |
436 | are several basic methods. | |
437 | .IP "1." 4 | |
438 | Anywhere you'd put an identifier (or chain of identifiers) as part | |
439 | of a variable or subroutine name, you can replace the identifier with | |
440 | a 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 | |
451 | It'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 | |
453 | scalar variable happens \fIbefore\fR it does any key lookups. Anything more | |
454 | complicated than a simple scalar variable must use methods 2 or 3 below. | |
455 | However, a \*(L"simple scalar\*(R" includes an identifier that itself uses method | |
456 | 1 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 | |
463 | Anywhere you'd put an identifier (or chain of identifiers) as part of a | |
464 | variable 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 | |
466 | previous 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 | |
477 | Admittedly, it's a little silly to use the curlies in this case, but | |
478 | the \s-1BLOCK\s0 can contain any arbitrary expression, in particular, | |
479 | subscripted expressions: | |
480 | .Sp | |
481 | .Vb 1 | |
482 | \& &{ $dispatch{$index} }(1,2,3); # call correct routine | |
483 | .Ve | |
484 | .Sp | |
485 | Because of being able to omit the curlies for the simple case of \f(CW$$x\fR, | |
486 | people often make the mistake of viewing the dereferencing symbols as | |
487 | proper operators, and wonder about their precedence. If they were, | |
488 | though, you could use parentheses instead of braces. That's not the case. | |
489 | Consider 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 | |
499 | Case 2 is also deceptive in that you're accessing a variable | |
500 | called \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hash | |
501 | it's presumably referencing. That would be case 3. | |
502 | .IP "3." 4 | |
503 | Subroutine calls and lookups of individual array elements arise often | |
504 | enough that it gets cumbersome to use method 2. As a form of | |
505 | syntactic 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 | |
513 | The left side of the arrow can be any expression returning a reference, | |
514 | including a previous dereference. Note that \f(CW$array[$x]\fR is \fInot\fR the | |
515 | same 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 | |
521 | This is one of the cases we mentioned earlier in which references could | |
522 | spring into existence when in an lvalue context. Before this | |
523 | statement, \f(CW$array[$x]\fR may have been undefined. If so, it's | |
524 | automatically 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 | |
526 | defined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it. | |
527 | This process is called \fIautovivification\fR. | |
528 | .Sp | |
529 | One more thing here. The arrow is optional \fIbetween\fR brackets | |
530 | subscripts, so you can shrink the above down to | |
531 | .Sp | |
532 | .Vb 1 | |
533 | \& $array[$x]{"foo"}[0] = "January"; | |
534 | .Ve | |
535 | .Sp | |
536 | Which, in the degenerate case of using only ordinary arrays, gives you | |
537 | multidimensional arrays just like C's: | |
538 | .Sp | |
539 | .Vb 1 | |
540 | \& $score[$x][$y][$z] += 42; | |
541 | .Ve | |
542 | .Sp | |
543 | Well, okay, not entirely like C's arrays, actually. C doesn't know how | |
544 | to grow its arrays on demand. Perl does. | |
545 | .IP "4." 4 | |
546 | If a reference happens to be a reference to an object, then there are | |
547 | probably methods to access the things referred to, and you should probably | |
548 | stick to those methods unless you're in the class package that defines the | |
549 | object's methods. In other words, be nice, and don't violate the object's | |
550 | encapsulation without a very good reason. Perl does not enforce | |
551 | encapsulation. We are not totalitarians here. We do expect some basic | |
552 | civility though. | |
553 | .PP | |
554 | Using a string or number as a reference produces a symbolic reference, | |
555 | as explained above. Using a reference as a number produces an | |
556 | integer representing its storage location in memory. The only | |
557 | useful thing to be done with this is to compare two references | |
558 | numerically 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 | |
566 | Using a reference as a string produces both its referent's type, | |
567 | including any package blessing as described in perlobj, as well | |
568 | as the numeric address expressed in hex. The \fIref()\fR operator returns | |
569 | just the type of thing the reference is pointing to, without the | |
570 | address. See \*(L"ref\*(R" in perlfunc for details and examples of its use. | |
571 | .PP | |
572 | The \fIbless()\fR operator may be used to associate the object a reference | |
573 | points to with a package functioning as an object class. See perlobj. | |
574 | .PP | |
575 | A typeglob may be dereferenced the same way a reference can, because | |
576 | the dereference syntax always indicates the type of reference desired. | |
577 | So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable. | |
578 | .PP | |
579 | Here'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 | |
585 | The way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quoted | |
586 | string, it's evaluated as a block. The block creates a reference to an | |
587 | anonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR. So | |
588 | the whole block returns a reference to an array, which is then | |
589 | dereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. This | |
590 | chicanery 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" | |
597 | We said that references spring into existence as necessary if they are | |
598 | undefined, but we didn't say what happens if a value used as a | |
599 | reference is already defined, but \fIisn't\fR a hard reference. If you | |
600 | use it as a reference, it'll be treated as a symbolic | |
601 | reference. That is, the value of the scalar is taken to be the \fIname\fR | |
602 | of a variable, rather than a direct link to a (possibly) anonymous | |
603 | value. | |
604 | .PP | |
605 | People 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 | |
619 | This is powerful, and slightly dangerous, in that it's possible | |
620 | to intend (with the utmost sincerity) to use a hard reference, and | |
621 | accidentally use a symbolic reference instead. To protect against | |
622 | that, you can say | |
623 | .PP | |
624 | .Vb 1 | |
625 | \& use strict 'refs'; | |
626 | .Ve | |
627 | .PP | |
628 | and then only hard references will be allowed for the rest of the enclosing | |
629 | block. An inner block may countermand that with | |
630 | .PP | |
631 | .Vb 1 | |
632 | \& no strict 'refs'; | |
633 | .Ve | |
634 | .PP | |
635 | Only package variables (globals, even if localized) are visible to | |
636 | symbolic references. Lexical variables (declared with \fImy()\fR) aren't in | |
637 | a 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 | |
648 | This will still print 10, not 20. Remember that \fIlocal()\fR affects package | |
649 | variables, which are all \*(L"global\*(R" to the package. | |
650 | .Sh "Not-so-symbolic references" | |
651 | .IX Subsection "Not-so-symbolic references" | |
652 | A new feature contributing to readability in perl version 5.001 is that the | |
653 | brackets around a symbolic reference behave more like quotes, just as they | |
654 | always have within a string. That is, | |
655 | .PP | |
656 | .Vb 2 | |
657 | \& $push = "pop on "; | |
658 | \& print "${push}over"; | |
659 | .Ve | |
660 | .PP | |
661 | has always meant to print \*(L"pop on over\*(R", even though push is | |
662 | a reserved word. This has been generalized to work the same outside | |
663 | of quotes, so that | |
664 | .PP | |
665 | .Vb 1 | |
666 | \& print ${push} . "over"; | |
667 | .Ve | |
668 | .PP | |
669 | and even | |
670 | .PP | |
671 | .Vb 1 | |
672 | \& print ${ push } . "over"; | |
673 | .Ve | |
674 | .PP | |
675 | will have the same effect. (This would have been a syntax error in | |
676 | Perl 5.000, though Perl 4 allowed it in the spaceless form.) This | |
677 | construct is \fInot\fR considered to be a symbolic reference when you're | |
678 | using 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 | |
686 | Similarly, because of all the subscripting that is done using single | |
687 | words, we've applied the same rule to any bareword that is used for | |
688 | subscripting a hash. So now, instead of writing | |
689 | .PP | |
690 | .Vb 1 | |
691 | \& $array{ "aaa" }{ "bbb" }{ "ccc" } | |
692 | .Ve | |
693 | .PP | |
694 | you can write just | |
695 | .PP | |
696 | .Vb 1 | |
697 | \& $array{ aaa }{ bbb }{ ccc } | |
698 | .Ve | |
699 | .PP | |
700 | and not worry about whether the subscripts are reserved words. In the | |
701 | rare event that you do wish to do something like | |
702 | .PP | |
703 | .Vb 1 | |
704 | \& $array{ shift } | |
705 | .Ve | |
706 | .PP | |
707 | you can force interpretation as a reserved word by adding anything that | |
708 | makes it more than a bareword: | |
709 | .PP | |
710 | .Vb 3 | |
711 | \& $array{ shift() } | |
712 | \& $array{ +shift } | |
713 | \& $array{ shift @_ } | |
714 | .Ve | |
715 | .PP | |
716 | The \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch will warn you if it | |
717 | interprets a reserved word as a string. | |
718 | But it will no longer warn you about using lowercase words, because the | |
719 | string 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 | |
723 | change 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 | |
727 | Perl 5.8.0 and will be removed in Perl 5.10.0, and the feature will be | |
728 | implemented differently. Not only is the current interface rather ugly, | |
729 | but the current implementation slows down normal array and hash use quite | |
730 | noticeably. The 'fields' pragma interface will remain available. | |
731 | .PP | |
732 | Beginning with release 5.005 of Perl, you may use an array reference | |
733 | in some contexts that would normally require a hash reference. This | |
734 | allows you to access array elements using symbolic names, as if they | |
735 | were fields in a structure. | |
736 | .PP | |
737 | For this to work, the array must contain extra information. The first | |
738 | element of the array has to be a hash reference that maps field names | |
739 | to 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 | |
761 | Perl will raise an exception if you try to access nonexistent fields. | |
762 | To avoid inconsistencies, always use the \fIfields::phash()\fR function | |
763 | provided 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 | |
770 | For better performance, Perl can also do the translation from field | |
771 | names to array indices at compile time for typed object references. | |
772 | See fields. | |
773 | .PP | |
774 | There are two ways to check for the existence of a key in a | |
775 | pseudo\-hash. The first is to use \fIexists()\fR. This checks to see if the | |
776 | given field has ever been set. It acts this way to match the behavior | |
777 | of 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 | |
791 | The second is to use \fIexists()\fR on the hash reference sitting in the | |
792 | first array element. This checks to see if the given key is a valid | |
793 | field 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 | |
801 | to the key, not the key itself. To delete the key, you'll have to | |
802 | explicitly 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" | |
813 | As explained above, a closure is an anonymous function with access to the | |
814 | lexical variables visible when that function was compiled. It retains | |
815 | access to those variables even though it doesn't get run until later, | |
816 | such as in a signal handler or a Tk callback. | |
817 | .PP | |
818 | Using a closure as a function template allows us to generate many functions | |
819 | that act similarly. Suppose you wanted functions named after the colors | |
820 | that 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 | |
826 | The \fIred()\fR and \fIgreen()\fR functions would be similar. To create these, | |
827 | we'll assign a closure to a typeglob of the name of the function we're | |
828 | trying 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 | |
838 | Now all those different functions appear to exist independently. You can | |
839 | call \fIred()\fR, \s-1\fIRED\s0()\fR, \fIblue()\fR, \s-1\fIBLUE\s0()\fR, \fIgreen()\fR, etc. This technique saves on | |
840 | both compile time and memory use, and is less error-prone as well, since | |
841 | syntax checks happen at compile time. It's critical that any variables in | |
842 | the anonymous subroutine be lexicals in order to create a proper closure. | |
843 | That's the reasons for the \f(CW\*(C`my\*(C'\fR on the loop iteration variable. | |
844 | .PP | |
845 | This is one of the only places where giving a prototype to a closure makes | |
846 | much sense. If you wanted to impose scalar context on the arguments of | |
847 | these functions (probably not a wise idea for this particular example), | |
848 | you could have written it this way instead: | |
849 | .PP | |
850 | .Vb 1 | |
851 | \& *$name = sub ($) { "<FONT COLOR='$name'>$_[0]</FONT>" }; | |
852 | .Ve | |
853 | .PP | |
854 | However, since prototype checking happens at compile time, the assignment | |
855 | above happens too late to be of much use. You could address this by | |
856 | putting the whole loop of assignments within a \s-1BEGIN\s0 block, forcing it | |
857 | to occur during compilation. | |
858 | .PP | |
859 | Access to lexicals that change over type\*(--like those in the \f(CW\*(C`for\*(C'\fR loop | |
860 | above\*(--only works with closures, not general subroutines. In the general | |
861 | case, then, named subroutines do not nest properly, although anonymous | |
862 | ones do. If you are accustomed to using nested subroutines in other | |
863 | programming languages with their own private variables, you'll have to | |
864 | work at it a bit in Perl. The intuitive coding of this type of thing | |
865 | incurs mysterious warnings about ``will not stay shared''. For example, | |
866 | this 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 | |
876 | A 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 | |
886 | Now \fIinner()\fR can only be called from within \fIouter()\fR, because of the | |
887 | temporary assignments of the closure (anonymous subroutine). But when | |
888 | it does, it has normal access to the lexical variable \f(CW$x\fR from the scope | |
889 | of \fIouter()\fR. | |
890 | .PP | |
891 | This has the interesting effect of creating a function local to another | |
892 | function, something not normally supported in Perl. | |
893 | .SH "WARNING" | |
894 | .IX Header "WARNING" | |
895 | You may not (usefully) use a reference as the key to a hash. It will be | |
896 | converted into a string: | |
897 | .PP | |
898 | .Vb 1 | |
899 | \& $x{ \e$a } = $a; | |
900 | .Ve | |
901 | .PP | |
902 | If you try to dereference the key, it won't do a hard dereference, and | |
903 | you won't accomplish what you're attempting. You might want to do something | |
904 | more like | |
905 | .PP | |
906 | .Vb 2 | |
907 | \& $r = \e@a; | |
908 | \& $x{ $r } = $r; | |
909 | .Ve | |
910 | .PP | |
911 | And then at least you can use the \fIvalues()\fR, which will be | |
912 | real refs, instead of the \fIkeys()\fR, which won't. | |
913 | .PP | |
914 | The standard Tie::RefHash module provides a convenient workaround to this. | |
915 | .SH "SEE ALSO" | |
916 | .IX Header "SEE ALSO" | |
917 | Besides the obvious documents, source code can be instructive. | |
918 | Some pathological examples of the use of references can be found | |
919 | in the \fIt/op/ref.t\fR regression test in the Perl source directory. | |
920 | .PP | |
921 | See also perldsc and perllol for how to use references to create | |
922 | complex data structures, and perltoot, perlobj, and perlbot | |
923 | for how to use them to create objects. |