| 1 |
.\" -*- mode: troff; coding: utf-8 -*- |
| 2 |
.\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45) |
| 3 |
.\" |
| 4 |
.\" Standard preamble: |
| 5 |
.\" ======================================================================== |
| 6 |
.de Sp \" Vertical space (when we can't use .PP) |
| 7 |
.if t .sp .5v |
| 8 |
.if n .sp |
| 9 |
.. |
| 10 |
.de Vb \" Begin verbatim text |
| 11 |
.ft CW |
| 12 |
.nf |
| 13 |
.ne \\$1 |
| 14 |
.. |
| 15 |
.de Ve \" End verbatim text |
| 16 |
.ft R |
| 17 |
.fi |
| 18 |
.. |
| 19 |
.\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. |
| 20 |
.ie n \{\ |
| 21 |
. ds C` "" |
| 22 |
. ds C' "" |
| 23 |
'br\} |
| 24 |
.el\{\ |
| 25 |
. ds C` |
| 26 |
. ds C' |
| 27 |
'br\} |
| 28 |
.\" |
| 29 |
.\" Escape single quotes in literal strings from groff's Unicode transform. |
| 30 |
.ie \n(.g .ds Aq \(aq |
| 31 |
.el .ds Aq ' |
| 32 |
.\" |
| 33 |
.\" If the F register is >0, we'll generate index entries on stderr for |
| 34 |
.\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index |
| 35 |
.\" entries marked with X<> in POD. Of course, you'll have to process the |
| 36 |
.\" output yourself in some meaningful fashion. |
| 37 |
.\" |
| 38 |
.\" Avoid warning from groff about undefined register 'F'. |
| 39 |
.de IX |
| 40 |
.. |
| 41 |
.nr rF 0 |
| 42 |
.if \n(.g .if rF .nr rF 1 |
| 43 |
.if (\n(rF:(\n(.g==0)) \{\ |
| 44 |
. if \nF \{\ |
| 45 |
. de IX |
| 46 |
. tm Index:\\$1\t\\n%\t"\\$2" |
| 47 |
.. |
| 48 |
. if !\nF==2 \{\ |
| 49 |
. nr % 0 |
| 50 |
. nr F 2 |
| 51 |
. \} |
| 52 |
. \} |
| 53 |
.\} |
| 54 |
.rr rF |
| 55 |
.\" ======================================================================== |
| 56 |
.\" |
| 57 |
.IX Title "PERLREF 1" |
| 58 |
.TH PERLREF 1 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide" |
| 59 |
.\" For nroff, turn off justification. Always turn off hyphenation; it makes |
| 60 |
.\" way too many mistakes in technical documents. |
| 61 |
.if n .ad l |
| 62 |
.nh |
| 63 |
.SH NAME |
| 64 |
perlref \- Perl references and nested data structures |
| 65 |
.IX Xref "reference pointer data structure structure struct" |
| 66 |
.SH NOTE |
| 67 |
.IX Header "NOTE" |
| 68 |
This is complete documentation about all aspects of references. |
| 69 |
For a shorter, tutorial introduction to just the essential features, |
| 70 |
see perlreftut. |
| 71 |
.SH DESCRIPTION |
| 72 |
.IX Header "DESCRIPTION" |
| 73 |
Before release 5 of Perl it was difficult to represent complex data |
| 74 |
structures, because all references had to be symbolic\-\-and even then |
| 75 |
it was difficult to refer to a variable instead of a symbol table entry. |
| 76 |
Perl now not only makes it easier to use symbolic references to variables, |
| 77 |
but also lets you have "hard" references to any piece of data or code. |
| 78 |
Any scalar may hold a hard reference. Because arrays and hashes contain |
| 79 |
scalars, you can now easily build arrays of arrays, arrays of hashes, |
| 80 |
hashes of arrays, arrays of hashes of functions, and so on. |
| 81 |
.PP |
| 82 |
Hard references are smart\-\-they keep track of reference counts for you, |
| 83 |
automatically freeing the thing referred to when its reference count goes |
| 84 |
to zero. (Reference counts for values in self-referential or |
| 85 |
cyclic data structures may not go to zero without a little help; see |
| 86 |
"Circular References" for a detailed explanation.) |
| 87 |
If that thing happens to be an object, the object is destructed. See |
| 88 |
perlobj for more about objects. (In a sense, everything in Perl is an |
| 89 |
object, but we usually reserve the word for references to objects that |
| 90 |
have been officially "blessed" into a class package.) |
| 91 |
.PP |
| 92 |
Symbolic references are names of variables or other objects, just as a |
| 93 |
symbolic link in a Unix filesystem contains merely the name of a file. |
| 94 |
The \f(CW*glob\fR notation is something of a symbolic reference. (Symbolic |
| 95 |
references are sometimes called "soft references", but please don't call |
| 96 |
them that; references are confusing enough without useless synonyms.) |
| 97 |
.IX Xref "reference, symbolic reference, soft symbolic reference soft reference" |
| 98 |
.PP |
| 99 |
In contrast, hard references are more like hard links in a Unix file |
| 100 |
system: They are used to access an underlying object without concern for |
| 101 |
what its (other) name is. When the word "reference" is used without an |
| 102 |
adjective, as in the following paragraph, it is usually talking about a |
| 103 |
hard reference. |
| 104 |
.IX Xref "reference, hard hard reference" |
| 105 |
.PP |
| 106 |
References are easy to use in Perl. There is just one overriding |
| 107 |
principle: in general, Perl does no implicit referencing or dereferencing. |
| 108 |
When a scalar is holding a reference, it always behaves as a simple scalar. |
| 109 |
It doesn't magically start being an array or hash or subroutine; you have to |
| 110 |
tell it explicitly to do so, by dereferencing it. |
| 111 |
.SS "Making References" |
| 112 |
.IX Xref "reference, creation referencing" |
| 113 |
.IX Subsection "Making References" |
| 114 |
References can be created in several ways. |
| 115 |
.PP |
| 116 |
\fIBackslash Operator\fR |
| 117 |
.IX Xref "\\ backslash" |
| 118 |
.IX Subsection "Backslash Operator" |
| 119 |
.PP |
| 120 |
By using the backslash operator on a variable, subroutine, or value. |
| 121 |
(This works much like the & (address-of) operator in C.) |
| 122 |
This typically creates \fIanother\fR reference to a variable, because |
| 123 |
there's already a reference to the variable in the symbol table. But |
| 124 |
the symbol table reference might go away, and you'll still have the |
| 125 |
reference that the backslash returned. Here are some examples: |
| 126 |
.PP |
| 127 |
.Vb 5 |
| 128 |
\& $scalarref = \e$foo; |
| 129 |
\& $arrayref = \e@ARGV; |
| 130 |
\& $hashref = \e%ENV; |
| 131 |
\& $coderef = \e&handler; |
| 132 |
\& $globref = \e*foo; |
| 133 |
.Ve |
| 134 |
.PP |
| 135 |
It isn't possible to create a true reference to an IO handle (filehandle |
| 136 |
or dirhandle) using the backslash operator. The most you can get is a |
| 137 |
reference to a typeglob, which is actually a complete symbol table entry. |
| 138 |
But see the explanation of the \f(CW*foo{THING}\fR syntax below. However, |
| 139 |
you can still use type globs and globrefs as though they were IO handles. |
| 140 |
.PP |
| 141 |
\fISquare Brackets\fR |
| 142 |
.IX Xref "array, anonymous [ [] square bracket bracket, square arrayref array reference reference, array" |
| 143 |
.IX Subsection "Square Brackets" |
| 144 |
.PP |
| 145 |
A reference to an anonymous array can be created using square |
| 146 |
brackets: |
| 147 |
.PP |
| 148 |
.Vb 1 |
| 149 |
\& $arrayref = [1, 2, [\*(Aqa\*(Aq, \*(Aqb\*(Aq, \*(Aqc\*(Aq]]; |
| 150 |
.Ve |
| 151 |
.PP |
| 152 |
Here we've created a reference to an anonymous array of three elements |
| 153 |
whose final element is itself a reference to another anonymous array of three |
| 154 |
elements. (The multidimensional syntax described later can be used to |
| 155 |
access this. For example, after the above, \f(CW\*(C`$arrayref\->[2][1]\*(C'\fR would have |
| 156 |
the value "b".) |
| 157 |
.PP |
| 158 |
Taking a reference to an enumerated list is not the same |
| 159 |
as using square brackets\-\-instead it's the same as creating |
| 160 |
a list of references! |
| 161 |
.PP |
| 162 |
.Vb 2 |
| 163 |
\& @list = (\e$x, \e@y, \e%z); |
| 164 |
\& @list = \e($x, @y, %z); # same thing! |
| 165 |
.Ve |
| 166 |
.PP |
| 167 |
As a special case, \f(CW\*(C`\e(@foo)\*(C'\fR returns a list of references to the contents |
| 168 |
of \f(CW@foo\fR, not a reference to \f(CW@foo\fR itself. Likewise for \f(CW%foo\fR, |
| 169 |
except that the key references are to copies (since the keys are just |
| 170 |
strings rather than full-fledged scalars). |
| 171 |
.PP |
| 172 |
\fICurly Brackets\fR |
| 173 |
.IX Xref "hash, anonymous { {} curly bracket bracket, curly brace hashref hash reference reference, hash" |
| 174 |
.IX Subsection "Curly Brackets" |
| 175 |
.PP |
| 176 |
A reference to an anonymous hash can be created using curly |
| 177 |
brackets: |
| 178 |
.PP |
| 179 |
.Vb 4 |
| 180 |
\& $hashref = { |
| 181 |
\& \*(AqAdam\*(Aq => \*(AqEve\*(Aq, |
| 182 |
\& \*(AqClyde\*(Aq => \*(AqBonnie\*(Aq, |
| 183 |
\& }; |
| 184 |
.Ve |
| 185 |
.PP |
| 186 |
Anonymous hash and array composers like these can be intermixed freely to |
| 187 |
produce as complicated a structure as you want. The multidimensional |
| 188 |
syntax described below works for these too. The values above are |
| 189 |
literals, but variables and expressions would work just as well, because |
| 190 |
assignment operators in Perl (even within \fBlocal()\fR or \fBmy()\fR) are executable |
| 191 |
statements, not compile-time declarations. |
| 192 |
.PP |
| 193 |
Because curly brackets (braces) are used for several other things |
| 194 |
including BLOCKs, you may occasionally have to disambiguate braces at the |
| 195 |
beginning of a statement by putting a \f(CW\*(C`+\*(C'\fR or a \f(CW\*(C`return\*(C'\fR in front so |
| 196 |
that Perl realizes the opening brace isn't starting a BLOCK. The economy and |
| 197 |
mnemonic value of using curlies is deemed worth this occasional extra |
| 198 |
hassle. |
| 199 |
.PP |
| 200 |
For example, if you wanted a function to make a new hash and return a |
| 201 |
reference to it, you have these options: |
| 202 |
.PP |
| 203 |
.Vb 3 |
| 204 |
\& sub hashem { { @_ } } # silently wrong |
| 205 |
\& sub hashem { +{ @_ } } # ok |
| 206 |
\& sub hashem { return { @_ } } # ok |
| 207 |
.Ve |
| 208 |
.PP |
| 209 |
On the other hand, if you want the other meaning, you can do this: |
| 210 |
.PP |
| 211 |
.Vb 4 |
| 212 |
\& sub showem { { @_ } } # ambiguous (currently ok, |
| 213 |
\& # but may change) |
| 214 |
\& sub showem { {; @_ } } # ok |
| 215 |
\& sub showem { { return @_ } } # ok |
| 216 |
.Ve |
| 217 |
.PP |
| 218 |
The leading \f(CW\*(C`+{\*(C'\fR and \f(CW\*(C`{;\*(C'\fR always serve to disambiguate |
| 219 |
the expression to mean either the HASH reference, or the BLOCK. |
| 220 |
.PP |
| 221 |
\fIAnonymous Subroutines\fR |
| 222 |
.IX Xref "subroutine, anonymous subroutine, reference reference, subroutine scope, lexical closure lexical lexical scope" |
| 223 |
.IX Subsection "Anonymous Subroutines" |
| 224 |
.PP |
| 225 |
A reference to an anonymous subroutine can be created by using |
| 226 |
\&\f(CW\*(C`sub\*(C'\fR without a subname: |
| 227 |
.PP |
| 228 |
.Vb 1 |
| 229 |
\& $coderef = sub { print "Boink!\en" }; |
| 230 |
.Ve |
| 231 |
.PP |
| 232 |
Note the semicolon. Except for the code |
| 233 |
inside not being immediately executed, a \f(CW\*(C`sub {}\*(C'\fR is not so much a |
| 234 |
declaration as it is an operator, like \f(CW\*(C`do{}\*(C'\fR or \f(CW\*(C`eval{}\*(C'\fR. (However, no |
| 235 |
matter how many times you execute that particular line (unless you're in an |
| 236 |
\&\f(CWeval("...")\fR), \f(CW$coderef\fR will still have a reference to the \fIsame\fR |
| 237 |
anonymous subroutine.) |
| 238 |
.PP |
| 239 |
Anonymous subroutines act as closures with respect to \fBmy()\fR variables, |
| 240 |
that is, variables lexically visible within the current scope. Closure |
| 241 |
is a notion out of the Lisp world that says if you define an anonymous |
| 242 |
function in a particular lexical context, it pretends to run in that |
| 243 |
context even when it's called outside the context. |
| 244 |
.PP |
| 245 |
In human terms, it's a funny way of passing arguments to a subroutine when |
| 246 |
you define it as well as when you call it. It's useful for setting up |
| 247 |
little bits of code to run later, such as callbacks. You can even |
| 248 |
do object-oriented stuff with it, though Perl already provides a different |
| 249 |
mechanism to do that\-\-see perlobj. |
| 250 |
.PP |
| 251 |
You might also think of closure as a way to write a subroutine |
| 252 |
template without using \fBeval()\fR. Here's a small example of how |
| 253 |
closures work: |
| 254 |
.PP |
| 255 |
.Vb 6 |
| 256 |
\& sub newprint { |
| 257 |
\& my $x = shift; |
| 258 |
\& return sub { my $y = shift; print "$x, $y!\en"; }; |
| 259 |
\& } |
| 260 |
\& $h = newprint("Howdy"); |
| 261 |
\& $g = newprint("Greetings"); |
| 262 |
\& |
| 263 |
\& # Time passes... |
| 264 |
\& |
| 265 |
\& &$h("world"); |
| 266 |
\& &$g("earthlings"); |
| 267 |
.Ve |
| 268 |
.PP |
| 269 |
This prints |
| 270 |
.PP |
| 271 |
.Vb 2 |
| 272 |
\& Howdy, world! |
| 273 |
\& Greetings, earthlings! |
| 274 |
.Ve |
| 275 |
.PP |
| 276 |
Note particularly that \f(CW$x\fR continues to refer to the value passed |
| 277 |
into \fBnewprint()\fR \fIdespite\fR "my \f(CW$x\fR" having gone out of scope by the |
| 278 |
time the anonymous subroutine runs. That's what a closure is all |
| 279 |
about. |
| 280 |
.PP |
| 281 |
This applies only to lexical variables, by the way. Dynamic variables |
| 282 |
continue to work as they have always worked. Closure is not something |
| 283 |
that most Perl programmers need trouble themselves about to begin with. |
| 284 |
.PP |
| 285 |
\fIConstructors\fR |
| 286 |
.IX Xref "constructor new" |
| 287 |
.IX Subsection "Constructors" |
| 288 |
.PP |
| 289 |
References are often returned by special subroutines called constructors. Perl |
| 290 |
objects are just references to a special type of object that happens to know |
| 291 |
which package it's associated with. Constructors are just special subroutines |
| 292 |
that know how to create that association. They do so by starting with an |
| 293 |
ordinary reference, and it remains an ordinary reference even while it's also |
| 294 |
being an object. Constructors are often named \f(CWnew()\fR. You \fIcan\fR call them |
| 295 |
indirectly: |
| 296 |
.PP |
| 297 |
.Vb 1 |
| 298 |
\& $objref = new Doggie( Tail => \*(Aqshort\*(Aq, Ears => \*(Aqlong\*(Aq ); |
| 299 |
.Ve |
| 300 |
.PP |
| 301 |
But that can produce ambiguous syntax in certain cases, so it's often |
| 302 |
better to use the direct method invocation approach: |
| 303 |
.PP |
| 304 |
.Vb 1 |
| 305 |
\& $objref = Doggie\->new(Tail => \*(Aqshort\*(Aq, Ears => \*(Aqlong\*(Aq); |
| 306 |
\& |
| 307 |
\& use Term::Cap; |
| 308 |
\& $terminal = Term::Cap\->Tgetent( { OSPEED => 9600 }); |
| 309 |
\& |
| 310 |
\& use Tk; |
| 311 |
\& $main = MainWindow\->new(); |
| 312 |
\& $menubar = $main\->Frame(\-relief => "raised", |
| 313 |
\& \-borderwidth => 2) |
| 314 |
.Ve |
| 315 |
.PP |
| 316 |
This indirect object syntax is only available when |
| 317 |
\&\f(CW\*(C`use feature "indirect"\*(C'\fR is in effect, |
| 318 |
and that is not the case when \f(CW\*(C`use v5.36\*(C'\fR (or |
| 319 |
higher) is requested, it is best to avoid indirect object syntax entirely. |
| 320 |
.PP |
| 321 |
\fIAutovivification\fR |
| 322 |
.IX Xref "autovivification" |
| 323 |
.IX Subsection "Autovivification" |
| 324 |
.PP |
| 325 |
References of the appropriate type can spring into existence if you |
| 326 |
dereference them in a context that assumes they exist. Because we haven't |
| 327 |
talked about dereferencing yet, we can't show you any examples yet. |
| 328 |
.PP |
| 329 |
\fITypeglob Slots\fR |
| 330 |
.IX Xref "*foo{THING} *" |
| 331 |
.IX Subsection "Typeglob Slots" |
| 332 |
.PP |
| 333 |
A reference can be created by using a special syntax, lovingly known as |
| 334 |
the *foo{THING} syntax. *foo{THING} returns a reference to the THING |
| 335 |
slot in *foo (which is the symbol table entry which holds everything |
| 336 |
known as foo). |
| 337 |
.PP |
| 338 |
.Vb 9 |
| 339 |
\& $scalarref = *foo{SCALAR}; |
| 340 |
\& $arrayref = *ARGV{ARRAY}; |
| 341 |
\& $hashref = *ENV{HASH}; |
| 342 |
\& $coderef = *handler{CODE}; |
| 343 |
\& $ioref = *STDIN{IO}; |
| 344 |
\& $globref = *foo{GLOB}; |
| 345 |
\& $formatref = *foo{FORMAT}; |
| 346 |
\& $globname = *foo{NAME}; # "foo" |
| 347 |
\& $pkgname = *foo{PACKAGE}; # "main" |
| 348 |
.Ve |
| 349 |
.PP |
| 350 |
Most of these are self-explanatory, but \f(CW*foo{IO}\fR |
| 351 |
deserves special attention. It returns |
| 352 |
the IO handle, used for file handles ("open" in perlfunc), sockets |
| 353 |
("socket" in perlfunc and "socketpair" in perlfunc), and directory |
| 354 |
handles ("opendir" in perlfunc). For compatibility with previous |
| 355 |
versions of Perl, \f(CW*foo{FILEHANDLE}\fR is a synonym for \f(CW*foo{IO}\fR, though it |
| 356 |
is discouraged, to encourage a consistent use of one name: IO. On perls |
| 357 |
between v5.8 and v5.22, it will issue a deprecation warning, but this |
| 358 |
deprecation has since been rescinded. |
| 359 |
.PP |
| 360 |
\&\f(CW*foo{THING}\fR returns undef if that particular THING hasn't been used yet, |
| 361 |
except in the case of scalars. \f(CW*foo{SCALAR}\fR returns a reference to an |
| 362 |
anonymous scalar if \f(CW$foo\fR hasn't been used yet. This might change in a |
| 363 |
future release. |
| 364 |
.PP |
| 365 |
\&\f(CW*foo{NAME}\fR and \f(CW*foo{PACKAGE}\fR are the exception, in that they return |
| 366 |
strings, rather than references. These return the package and name of the |
| 367 |
typeglob itself, rather than one that has been assigned to it. So, after |
| 368 |
\&\f(CW\*(C`*foo=*Foo::bar\*(C'\fR, \f(CW*foo\fR will become "*Foo::bar" when used as a string, |
| 369 |
but \f(CW*foo{PACKAGE}\fR and \f(CW*foo{NAME}\fR will continue to produce "main" and |
| 370 |
"foo", respectively. |
| 371 |
.PP |
| 372 |
\&\f(CW*foo{IO}\fR is an alternative to the \f(CW*HANDLE\fR mechanism given in |
| 373 |
"Typeglobs and Filehandles" in perldata for passing filehandles |
| 374 |
into or out of subroutines, or storing into larger data structures. |
| 375 |
Its disadvantage is that it won't create a new filehandle for you. |
| 376 |
Its advantage is that you have less risk of clobbering more than |
| 377 |
you want to with a typeglob assignment. (It still conflates file |
| 378 |
and directory handles, though.) However, if you assign the incoming |
| 379 |
value to a scalar instead of a typeglob as we do in the examples |
| 380 |
below, there's no risk of that happening. |
| 381 |
.PP |
| 382 |
.Vb 2 |
| 383 |
\& splutter(*STDOUT); # pass the whole glob |
| 384 |
\& splutter(*STDOUT{IO}); # pass both file and dir handles |
| 385 |
\& |
| 386 |
\& sub splutter { |
| 387 |
\& my $fh = shift; |
| 388 |
\& print $fh "her um well a hmmm\en"; |
| 389 |
\& } |
| 390 |
\& |
| 391 |
\& $rec = get_rec(*STDIN); # pass the whole glob |
| 392 |
\& $rec = get_rec(*STDIN{IO}); # pass both file and dir handles |
| 393 |
\& |
| 394 |
\& sub get_rec { |
| 395 |
\& my $fh = shift; |
| 396 |
\& return scalar <$fh>; |
| 397 |
\& } |
| 398 |
.Ve |
| 399 |
.SS "Using References" |
| 400 |
.IX Xref "reference, use dereferencing dereference" |
| 401 |
.IX Subsection "Using References" |
| 402 |
That's it for creating references. By now you're probably dying to |
| 403 |
know how to use references to get back to your long-lost data. There |
| 404 |
are several basic methods. |
| 405 |
.PP |
| 406 |
\fISimple Scalar\fR |
| 407 |
.IX Subsection "Simple Scalar" |
| 408 |
.PP |
| 409 |
Anywhere you'd put an identifier (or chain of identifiers) as part |
| 410 |
of a variable or subroutine name, you can replace the identifier with |
| 411 |
a simple scalar variable containing a reference of the correct type: |
| 412 |
.PP |
| 413 |
.Vb 6 |
| 414 |
\& $bar = $$scalarref; |
| 415 |
\& push(@$arrayref, $filename); |
| 416 |
\& $$arrayref[0] = "January"; |
| 417 |
\& $$hashref{"KEY"} = "VALUE"; |
| 418 |
\& &$coderef(1,2,3); |
| 419 |
\& print $globref "output\en"; |
| 420 |
.Ve |
| 421 |
.PP |
| 422 |
It's important to understand that we are specifically \fInot\fR dereferencing |
| 423 |
\&\f(CW$arrayref[0]\fR or \f(CW$hashref{"KEY"}\fR there. The dereference of the |
| 424 |
scalar variable happens \fIbefore\fR it does any key lookups. Anything more |
| 425 |
complicated than a simple scalar variable must use methods 2 or 3 below. |
| 426 |
However, a "simple scalar" includes an identifier that itself uses method |
| 427 |
1 recursively. Therefore, the following prints "howdy". |
| 428 |
.PP |
| 429 |
.Vb 2 |
| 430 |
\& $refrefref = \e\e\e"howdy"; |
| 431 |
\& print $$$$refrefref; |
| 432 |
.Ve |
| 433 |
.PP |
| 434 |
\fIBlock\fR |
| 435 |
.IX Subsection "Block" |
| 436 |
.PP |
| 437 |
Anywhere you'd put an identifier (or chain of identifiers) as part of a |
| 438 |
variable or subroutine name, you can replace the identifier with a |
| 439 |
BLOCK returning a reference of the correct type. In other words, the |
| 440 |
previous examples could be written like this: |
| 441 |
.PP |
| 442 |
.Vb 6 |
| 443 |
\& $bar = ${$scalarref}; |
| 444 |
\& push(@{$arrayref}, $filename); |
| 445 |
\& ${$arrayref}[0] = "January"; |
| 446 |
\& ${$hashref}{"KEY"} = "VALUE"; |
| 447 |
\& &{$coderef}(1,2,3); |
| 448 |
\& $globref\->print("output\en"); # iff IO::Handle is loaded |
| 449 |
.Ve |
| 450 |
.PP |
| 451 |
Admittedly, it's a little silly to use the curlies in this case, but |
| 452 |
the BLOCK can contain any arbitrary expression, in particular, |
| 453 |
subscripted expressions: |
| 454 |
.PP |
| 455 |
.Vb 1 |
| 456 |
\& &{ $dispatch{$index} }(1,2,3); # call correct routine |
| 457 |
.Ve |
| 458 |
.PP |
| 459 |
Because of being able to omit the curlies for the simple case of \f(CW$$x\fR, |
| 460 |
people often make the mistake of viewing the dereferencing symbols as |
| 461 |
proper operators, and wonder about their precedence. If they were, |
| 462 |
though, you could use parentheses instead of braces. That's not the case. |
| 463 |
Consider the difference below; case 0 is a short-hand version of case 1, |
| 464 |
\&\fInot\fR case 2: |
| 465 |
.PP |
| 466 |
.Vb 4 |
| 467 |
\& $$hashref{"KEY"} = "VALUE"; # CASE 0 |
| 468 |
\& ${$hashref}{"KEY"} = "VALUE"; # CASE 1 |
| 469 |
\& ${$hashref{"KEY"}} = "VALUE"; # CASE 2 |
| 470 |
\& ${$hashref\->{"KEY"}} = "VALUE"; # CASE 3 |
| 471 |
.Ve |
| 472 |
.PP |
| 473 |
Case 2 is also deceptive in that you're accessing a variable |
| 474 |
called \f(CW%hashref\fR, not dereferencing through \f(CW$hashref\fR to the hash |
| 475 |
it's presumably referencing. That would be case 3. |
| 476 |
.PP |
| 477 |
\fIArrow Notation\fR |
| 478 |
.IX Subsection "Arrow Notation" |
| 479 |
.PP |
| 480 |
Subroutine calls and lookups of individual array elements arise often |
| 481 |
enough that it gets cumbersome to use method 2. As a form of |
| 482 |
syntactic sugar, the examples for method 2 may be written: |
| 483 |
.PP |
| 484 |
.Vb 3 |
| 485 |
\& $arrayref\->[0] = "January"; # Array element |
| 486 |
\& $hashref\->{"KEY"} = "VALUE"; # Hash element |
| 487 |
\& $coderef\->(1,2,3); # Subroutine call |
| 488 |
.Ve |
| 489 |
.PP |
| 490 |
The left side of the arrow can be any expression returning a reference, |
| 491 |
including a previous dereference. Note that \f(CW$array[$x]\fR is \fInot\fR the |
| 492 |
same thing as \f(CW\*(C`$array\->[$x]\*(C'\fR here: |
| 493 |
.PP |
| 494 |
.Vb 1 |
| 495 |
\& $array[$x]\->{"foo"}\->[0] = "January"; |
| 496 |
.Ve |
| 497 |
.PP |
| 498 |
This is one of the cases we mentioned earlier in which references could |
| 499 |
spring into existence when in an lvalue context. Before this |
| 500 |
statement, \f(CW$array[$x]\fR may have been undefined. If so, it's |
| 501 |
automatically defined with a hash reference so that we can look up |
| 502 |
\&\f(CW\*(C`{"foo"}\*(C'\fR in it. Likewise \f(CW\*(C`$array[$x]\->{"foo"}\*(C'\fR will automatically get |
| 503 |
defined with an array reference so that we can look up \f(CW\*(C`[0]\*(C'\fR in it. |
| 504 |
This process is called \fIautovivification\fR. |
| 505 |
.PP |
| 506 |
One more thing here. The arrow is optional \fIbetween\fR brackets |
| 507 |
subscripts, so you can shrink the above down to |
| 508 |
.PP |
| 509 |
.Vb 1 |
| 510 |
\& $array[$x]{"foo"}[0] = "January"; |
| 511 |
.Ve |
| 512 |
.PP |
| 513 |
Which, in the degenerate case of using only ordinary arrays, gives you |
| 514 |
multidimensional arrays just like C's: |
| 515 |
.PP |
| 516 |
.Vb 1 |
| 517 |
\& $score[$x][$y][$z] += 42; |
| 518 |
.Ve |
| 519 |
.PP |
| 520 |
Well, okay, not entirely like C's arrays, actually. C doesn't know how |
| 521 |
to grow its arrays on demand. Perl does. |
| 522 |
.PP |
| 523 |
\fIObjects\fR |
| 524 |
.IX Subsection "Objects" |
| 525 |
.PP |
| 526 |
If a reference happens to be a reference to an object, then there are |
| 527 |
probably methods to access the things referred to, and you should probably |
| 528 |
stick to those methods unless you're in the class package that defines the |
| 529 |
object's methods. In other words, be nice, and don't violate the object's |
| 530 |
encapsulation without a very good reason. Perl does not enforce |
| 531 |
encapsulation. We are not totalitarians here. We do expect some basic |
| 532 |
civility though. |
| 533 |
.PP |
| 534 |
\fIMiscellaneous Usage\fR |
| 535 |
.IX Subsection "Miscellaneous Usage" |
| 536 |
.PP |
| 537 |
Using a string or number as a reference produces a symbolic reference, |
| 538 |
as explained above. Using a reference as a number produces an |
| 539 |
integer representing its storage location in memory. The only |
| 540 |
useful thing to be done with this is to compare two references |
| 541 |
numerically to see whether they refer to the same location. |
| 542 |
.IX Xref "reference, numeric context" |
| 543 |
.PP |
| 544 |
.Vb 3 |
| 545 |
\& if ($ref1 == $ref2) { # cheap numeric compare of references |
| 546 |
\& print "refs 1 and 2 refer to the same thing\en"; |
| 547 |
\& } |
| 548 |
.Ve |
| 549 |
.PP |
| 550 |
Using a reference as a string produces both its referent's type, |
| 551 |
including any package blessing as described in perlobj, as well |
| 552 |
as the numeric address expressed in hex. The \fBref()\fR operator returns |
| 553 |
just the type of thing the reference is pointing to, without the |
| 554 |
address. See "ref" in perlfunc for details and examples of its use. |
| 555 |
.IX Xref "reference, string context" |
| 556 |
.PP |
| 557 |
The \fBbless()\fR operator may be used to associate the object a reference |
| 558 |
points to with a package functioning as an object class. See perlobj. |
| 559 |
.PP |
| 560 |
A typeglob may be dereferenced the same way a reference can, because |
| 561 |
the dereference syntax always indicates the type of reference desired. |
| 562 |
So \f(CW\*(C`${*foo}\*(C'\fR and \f(CW\*(C`${\e$foo}\*(C'\fR both indicate the same scalar variable. |
| 563 |
.PP |
| 564 |
Here's a trick for interpolating a subroutine call into a string: |
| 565 |
.PP |
| 566 |
.Vb 1 |
| 567 |
\& print "My sub returned @{[mysub(1,2,3)]} that time.\en"; |
| 568 |
.Ve |
| 569 |
.PP |
| 570 |
The way it works is that when the \f(CW\*(C`@{...}\*(C'\fR is seen in the double-quoted |
| 571 |
string, it's evaluated as a block. The block creates a reference to an |
| 572 |
anonymous array containing the results of the call to \f(CW\*(C`mysub(1,2,3)\*(C'\fR. So |
| 573 |
the whole block returns a reference to an array, which is then |
| 574 |
dereferenced by \f(CW\*(C`@{...}\*(C'\fR and stuck into the double-quoted string. This |
| 575 |
chicanery is also useful for arbitrary expressions: |
| 576 |
.PP |
| 577 |
.Vb 1 |
| 578 |
\& print "That yields @{[$n + 5]} widgets\en"; |
| 579 |
.Ve |
| 580 |
.PP |
| 581 |
Similarly, an expression that returns a reference to a scalar can be |
| 582 |
dereferenced via \f(CW\*(C`${...}\*(C'\fR. Thus, the above expression may be written |
| 583 |
as: |
| 584 |
.PP |
| 585 |
.Vb 1 |
| 586 |
\& print "That yields ${\e($n + 5)} widgets\en"; |
| 587 |
.Ve |
| 588 |
.SS "Circular References" |
| 589 |
.IX Xref "circular reference reference, circular" |
| 590 |
.IX Subsection "Circular References" |
| 591 |
It is possible to create a "circular reference" in Perl, which can lead |
| 592 |
to memory leaks. A circular reference occurs when two references |
| 593 |
contain a reference to each other, like this: |
| 594 |
.PP |
| 595 |
.Vb 3 |
| 596 |
\& my $foo = {}; |
| 597 |
\& my $bar = { foo => $foo }; |
| 598 |
\& $foo\->{bar} = $bar; |
| 599 |
.Ve |
| 600 |
.PP |
| 601 |
You can also create a circular reference with a single variable: |
| 602 |
.PP |
| 603 |
.Vb 2 |
| 604 |
\& my $foo; |
| 605 |
\& $foo = \e$foo; |
| 606 |
.Ve |
| 607 |
.PP |
| 608 |
In this case, the reference count for the variables will never reach 0, |
| 609 |
and the references will never be garbage-collected. This can lead to |
| 610 |
memory leaks. |
| 611 |
.PP |
| 612 |
Because objects in Perl are implemented as references, it's possible to |
| 613 |
have circular references with objects as well. Imagine a TreeNode class |
| 614 |
where each node references its parent and child nodes. Any node with a |
| 615 |
parent will be part of a circular reference. |
| 616 |
.PP |
| 617 |
You can break circular references by creating a "weak reference". A |
| 618 |
weak reference does not increment the reference count for a variable, |
| 619 |
which means that the object can go out of scope and be destroyed. You |
| 620 |
can weaken a reference with the \f(CW\*(C`weaken\*(C'\fR function exported by the |
| 621 |
Scalar::Util module, or available as \f(CW\*(C`builtin::weaken\*(C'\fR directly in |
| 622 |
Perl version 5.35.7 or later. |
| 623 |
.PP |
| 624 |
Here's how we can make the first example safer: |
| 625 |
.PP |
| 626 |
.Vb 1 |
| 627 |
\& use Scalar::Util \*(Aqweaken\*(Aq; |
| 628 |
\& |
| 629 |
\& my $foo = {}; |
| 630 |
\& my $bar = { foo => $foo }; |
| 631 |
\& $foo\->{bar} = $bar; |
| 632 |
\& |
| 633 |
\& weaken $foo\->{bar}; |
| 634 |
.Ve |
| 635 |
.PP |
| 636 |
The reference from \f(CW$foo\fR to \f(CW$bar\fR has been weakened. When the |
| 637 |
\&\f(CW$bar\fR variable goes out of scope, it will be garbage-collected. The |
| 638 |
next time you look at the value of the \f(CW\*(C`$foo\->{bar}\*(C'\fR key, it will |
| 639 |
be \f(CW\*(C`undef\*(C'\fR. |
| 640 |
.PP |
| 641 |
This action at a distance can be confusing, so you should be careful |
| 642 |
with your use of weaken. You should weaken the reference in the |
| 643 |
variable that will go out of scope \fIfirst\fR. That way, the longer-lived |
| 644 |
variable will contain the expected reference until it goes out of |
| 645 |
scope. |
| 646 |
.SS "Symbolic references" |
| 647 |
.IX Xref "reference, symbolic reference, soft symbolic reference soft reference" |
| 648 |
.IX Subsection "Symbolic references" |
| 649 |
We said that references spring into existence as necessary if they are |
| 650 |
undefined, but we didn't say what happens if a value used as a |
| 651 |
reference is already defined, but \fIisn't\fR a hard reference. If you |
| 652 |
use it as a reference, it'll be treated as a symbolic |
| 653 |
reference. That is, the value of the scalar is taken to be the \fIname\fR |
| 654 |
of a variable, rather than a direct link to a (possibly) anonymous |
| 655 |
value. |
| 656 |
.PP |
| 657 |
People frequently expect it to work like this. So it does. |
| 658 |
.PP |
| 659 |
.Vb 9 |
| 660 |
\& $name = "foo"; |
| 661 |
\& $$name = 1; # Sets $foo |
| 662 |
\& ${$name} = 2; # Sets $foo |
| 663 |
\& ${$name x 2} = 3; # Sets $foofoo |
| 664 |
\& $name\->[0] = 4; # Sets $foo[0] |
| 665 |
\& @$name = (); # Clears @foo |
| 666 |
\& &$name(); # Calls &foo() |
| 667 |
\& $pack = "THAT"; |
| 668 |
\& ${"${pack}::$name"} = 5; # Sets $THAT::foo without eval |
| 669 |
.Ve |
| 670 |
.PP |
| 671 |
This is powerful, and slightly dangerous, in that it's possible |
| 672 |
to intend (with the utmost sincerity) to use a hard reference, and |
| 673 |
accidentally use a symbolic reference instead. To protect against |
| 674 |
that, you can say |
| 675 |
.PP |
| 676 |
.Vb 1 |
| 677 |
\& use strict \*(Aqrefs\*(Aq; |
| 678 |
.Ve |
| 679 |
.PP |
| 680 |
and then only hard references will be allowed for the rest of the enclosing |
| 681 |
block. An inner block may countermand that with |
| 682 |
.PP |
| 683 |
.Vb 1 |
| 684 |
\& no strict \*(Aqrefs\*(Aq; |
| 685 |
.Ve |
| 686 |
.PP |
| 687 |
Only package variables (globals, even if localized) are visible to |
| 688 |
symbolic references. Lexical variables (declared with \fBmy()\fR) aren't in |
| 689 |
a symbol table, and thus are invisible to this mechanism. For example: |
| 690 |
.PP |
| 691 |
.Vb 6 |
| 692 |
\& local $value = 10; |
| 693 |
\& $ref = "value"; |
| 694 |
\& { |
| 695 |
\& my $value = 20; |
| 696 |
\& print $$ref; |
| 697 |
\& } |
| 698 |
.Ve |
| 699 |
.PP |
| 700 |
This will still print 10, not 20. Remember that \fBlocal()\fR affects package |
| 701 |
variables, which are all "global" to the package. |
| 702 |
.SS "Not-so-symbolic references" |
| 703 |
.IX Subsection "Not-so-symbolic references" |
| 704 |
Brackets around a symbolic reference can simply |
| 705 |
serve to isolate an identifier or variable name from the rest of an |
| 706 |
expression, just as they always have within a string. For example, |
| 707 |
.PP |
| 708 |
.Vb 2 |
| 709 |
\& $push = "pop on "; |
| 710 |
\& print "${push}over"; |
| 711 |
.Ve |
| 712 |
.PP |
| 713 |
has always meant to print "pop on over", even though push is |
| 714 |
a reserved word. This is generalized to work the same |
| 715 |
without the enclosing double quotes, so that |
| 716 |
.PP |
| 717 |
.Vb 1 |
| 718 |
\& print ${push} . "over"; |
| 719 |
.Ve |
| 720 |
.PP |
| 721 |
and even |
| 722 |
.PP |
| 723 |
.Vb 1 |
| 724 |
\& print ${ push } . "over"; |
| 725 |
.Ve |
| 726 |
.PP |
| 727 |
will have the same effect. This |
| 728 |
construct is \fInot\fR considered to be a symbolic reference when you're |
| 729 |
using strict refs: |
| 730 |
.PP |
| 731 |
.Vb 3 |
| 732 |
\& use strict \*(Aqrefs\*(Aq; |
| 733 |
\& ${ bareword }; # Okay, means $bareword. |
| 734 |
\& ${ "bareword" }; # Error, symbolic reference. |
| 735 |
.Ve |
| 736 |
.PP |
| 737 |
Similarly, because of all the subscripting that is done using single words, |
| 738 |
the same rule applies to any bareword that is used for subscripting a hash. |
| 739 |
So now, instead of writing |
| 740 |
.PP |
| 741 |
.Vb 1 |
| 742 |
\& $hash{ "aaa" }{ "bbb" }{ "ccc" } |
| 743 |
.Ve |
| 744 |
.PP |
| 745 |
you can write just |
| 746 |
.PP |
| 747 |
.Vb 1 |
| 748 |
\& $hash{ aaa }{ bbb }{ ccc } |
| 749 |
.Ve |
| 750 |
.PP |
| 751 |
and not worry about whether the subscripts are reserved words. In the |
| 752 |
rare event that you do wish to do something like |
| 753 |
.PP |
| 754 |
.Vb 1 |
| 755 |
\& $hash{ shift } |
| 756 |
.Ve |
| 757 |
.PP |
| 758 |
you can force interpretation as a reserved word by adding anything that |
| 759 |
makes it more than a bareword: |
| 760 |
.PP |
| 761 |
.Vb 3 |
| 762 |
\& $hash{ shift() } |
| 763 |
\& $hash{ +shift } |
| 764 |
\& $hash{ shift @_ } |
| 765 |
.Ve |
| 766 |
.PP |
| 767 |
The \f(CW\*(C`use warnings\*(C'\fR pragma or the \fB\-w\fR switch will warn you if it |
| 768 |
interprets a reserved word as a string. |
| 769 |
But it will no longer warn you about using lowercase words, because the |
| 770 |
string is effectively quoted. |
| 771 |
.SS "Pseudo-hashes: Using an array as a hash" |
| 772 |
.IX Xref "pseudo-hash pseudo hash pseudohash" |
| 773 |
.IX Subsection "Pseudo-hashes: Using an array as a hash" |
| 774 |
Pseudo-hashes have been removed from Perl. The 'fields' pragma |
| 775 |
remains available. |
| 776 |
.SS "Function Templates" |
| 777 |
.IX Xref "scope, lexical closure lexical lexical scope subroutine, nested sub, nested subroutine, local sub, local" |
| 778 |
.IX Subsection "Function Templates" |
| 779 |
As explained above, an anonymous function with access to the lexical |
| 780 |
variables visible when that function was compiled, creates a closure. It |
| 781 |
retains access to those variables even though it doesn't get run until |
| 782 |
later, such as in a signal handler or a Tk callback. |
| 783 |
.PP |
| 784 |
Using a closure as a function template allows us to generate many functions |
| 785 |
that act similarly. Suppose you wanted functions named after the colors |
| 786 |
that generated HTML font changes for the various colors: |
| 787 |
.PP |
| 788 |
.Vb 1 |
| 789 |
\& print "Be ", red("careful"), "with that ", green("light"); |
| 790 |
.Ve |
| 791 |
.PP |
| 792 |
The \fBred()\fR and \fBgreen()\fR functions would be similar. To create these, |
| 793 |
we'll assign a closure to a typeglob of the name of the function we're |
| 794 |
trying to build. |
| 795 |
.PP |
| 796 |
.Vb 5 |
| 797 |
\& @colors = qw(red blue green yellow orange purple violet); |
| 798 |
\& for my $name (@colors) { |
| 799 |
\& no strict \*(Aqrefs\*(Aq; # allow symbol table manipulation |
| 800 |
\& *$name = *{uc $name} = sub { "<FONT COLOR=\*(Aq$name\*(Aq>@_</FONT>" }; |
| 801 |
\& } |
| 802 |
.Ve |
| 803 |
.PP |
| 804 |
Now all those different functions appear to exist independently. You can |
| 805 |
call \fBred()\fR, \fBRED()\fR, \fBblue()\fR, \fBBLUE()\fR, \fBgreen()\fR, etc. This technique saves on |
| 806 |
both compile time and memory use, and is less error-prone as well, since |
| 807 |
syntax checks happen at compile time. It's critical that any variables in |
| 808 |
the anonymous subroutine be lexicals in order to create a proper closure. |
| 809 |
That's the reasons for the \f(CW\*(C`my\*(C'\fR on the loop iteration variable. |
| 810 |
.PP |
| 811 |
This is one of the only places where giving a prototype to a closure makes |
| 812 |
much sense. If you wanted to impose scalar context on the arguments of |
| 813 |
these functions (probably not a wise idea for this particular example), |
| 814 |
you could have written it this way instead: |
| 815 |
.PP |
| 816 |
.Vb 1 |
| 817 |
\& *$name = sub ($) { "<FONT COLOR=\*(Aq$name\*(Aq>$_[0]</FONT>" }; |
| 818 |
.Ve |
| 819 |
.PP |
| 820 |
However, since prototype checking happens at compile time, the assignment |
| 821 |
above happens too late to be of much use. You could address this by |
| 822 |
putting the whole loop of assignments within a BEGIN block, forcing it |
| 823 |
to occur during compilation. |
| 824 |
.PP |
| 825 |
Access to lexicals that change over time\-\-like those in the \f(CW\*(C`for\*(C'\fR loop |
| 826 |
above, basically aliases to elements from the surrounding lexical scopes\-\- |
| 827 |
only works with anonymous subs, not with named subroutines. Generally |
| 828 |
said, named subroutines do not nest properly and should only be declared |
| 829 |
in the main package scope. |
| 830 |
.PP |
| 831 |
This is because named subroutines are created at compile time so their |
| 832 |
lexical variables get assigned to the parent lexicals from the first |
| 833 |
execution of the parent block. If a parent scope is entered a second |
| 834 |
time, its lexicals are created again, while the nested subs still |
| 835 |
reference the old ones. |
| 836 |
.PP |
| 837 |
Anonymous subroutines get to capture each time you execute the \f(CW\*(C`sub\*(C'\fR |
| 838 |
operator, as they are created on the fly. If you are accustomed to using |
| 839 |
nested subroutines in other programming languages with their own private |
| 840 |
variables, you'll have to work at it a bit in Perl. The intuitive coding |
| 841 |
of this type of thing incurs mysterious warnings about "will not stay |
| 842 |
shared" due to the reasons explained above. |
| 843 |
For example, this won't work: |
| 844 |
.PP |
| 845 |
.Vb 5 |
| 846 |
\& sub outer { |
| 847 |
\& my $x = $_[0] + 35; |
| 848 |
\& sub inner { return $x * 19 } # WRONG |
| 849 |
\& return $x + inner(); |
| 850 |
\& } |
| 851 |
.Ve |
| 852 |
.PP |
| 853 |
A work-around is the following: |
| 854 |
.PP |
| 855 |
.Vb 5 |
| 856 |
\& sub outer { |
| 857 |
\& my $x = $_[0] + 35; |
| 858 |
\& local *inner = sub { return $x * 19 }; |
| 859 |
\& return $x + inner(); |
| 860 |
\& } |
| 861 |
.Ve |
| 862 |
.PP |
| 863 |
Now \fBinner()\fR can only be called from within \fBouter()\fR, because of the |
| 864 |
temporary assignments of the anonymous subroutine. But when it does, |
| 865 |
it has normal access to the lexical variable \f(CW$x\fR from the scope of |
| 866 |
\&\fBouter()\fR at the time outer is invoked. |
| 867 |
.PP |
| 868 |
This has the interesting effect of creating a function local to another |
| 869 |
function, something not normally supported in Perl. |
| 870 |
.SS "Postfix Dereference Syntax" |
| 871 |
.IX Subsection "Postfix Dereference Syntax" |
| 872 |
Beginning in v5.20.0, a postfix syntax for using references is |
| 873 |
available. It behaves as described in "Using References", but instead |
| 874 |
of a prefixed sigil, a postfixed sigil-and-star is used. |
| 875 |
.PP |
| 876 |
For example: |
| 877 |
.PP |
| 878 |
.Vb 2 |
| 879 |
\& $r = \e@a; |
| 880 |
\& @b = $r\->@*; # equivalent to @$r or @{ $r } |
| 881 |
\& |
| 882 |
\& $r = [ 1, [ 2, 3 ], 4 ]; |
| 883 |
\& $r\->[1]\->@*; # equivalent to @{ $r\->[1] } |
| 884 |
.Ve |
| 885 |
.PP |
| 886 |
In Perl 5.20 and 5.22, this syntax must be enabled with \f(CWuse feature |
| 887 |
\&\*(Aqpostderef\*(Aq\fR. As of Perl 5.24, no feature declarations are required to make |
| 888 |
it available. |
| 889 |
.PP |
| 890 |
Postfix dereference should work in all circumstances where block |
| 891 |
(circumfix) dereference worked, and should be entirely equivalent. This |
| 892 |
syntax allows dereferencing to be written and read entirely |
| 893 |
left-to-right. The following equivalencies are defined: |
| 894 |
.PP |
| 895 |
.Vb 6 |
| 896 |
\& $sref\->$*; # same as ${ $sref } |
| 897 |
\& $aref\->@*; # same as @{ $aref } |
| 898 |
\& $aref\->$#*; # same as $#{ $aref } |
| 899 |
\& $href\->%*; # same as %{ $href } |
| 900 |
\& $cref\->&*; # same as &{ $cref } |
| 901 |
\& $gref\->**; # same as *{ $gref } |
| 902 |
.Ve |
| 903 |
.PP |
| 904 |
Note especially that \f(CW\*(C`$cref\->&*\*(C'\fR is \fInot\fR equivalent to \f(CW$cref\->()\fR, and can serve different purposes. |
| 905 |
.PP |
| 906 |
Glob elements can be extracted through the postfix dereferencing feature: |
| 907 |
.PP |
| 908 |
.Vb 1 |
| 909 |
\& $gref\->*{SCALAR}; # same as *{ $gref }{SCALAR} |
| 910 |
.Ve |
| 911 |
.PP |
| 912 |
Postfix array and scalar dereferencing \fIcan\fR be used in interpolating |
| 913 |
strings (double quotes or the \f(CW\*(C`qq\*(C'\fR operator), but only if the |
| 914 |
\&\f(CW\*(C`postderef_qq\*(C'\fR feature is enabled. Interpolation of postfix array highest index |
| 915 |
access (\f(CW\*(C`\->$#*\*(C'\fR) is also supported when the \f(CW\*(C`postderef_qq\*(C'\fR feature is |
| 916 |
enabled. |
| 917 |
.SS "Postfix Reference Slicing" |
| 918 |
.IX Subsection "Postfix Reference Slicing" |
| 919 |
Value slices of arrays and hashes may also be taken with postfix |
| 920 |
dereferencing notation, with the following equivalencies: |
| 921 |
.PP |
| 922 |
.Vb 2 |
| 923 |
\& $aref\->@[ ... ]; # same as @$aref[ ... ] |
| 924 |
\& $href\->@{ ... }; # same as @$href{ ... } |
| 925 |
.Ve |
| 926 |
.PP |
| 927 |
Postfix key/value pair slicing, added in 5.20.0 and documented in |
| 928 |
the Key/Value Hash Slices section of perldata, also behaves as expected: |
| 929 |
.PP |
| 930 |
.Vb 2 |
| 931 |
\& $aref\->%[ ... ]; # same as %$aref[ ... ] |
| 932 |
\& $href\->%{ ... }; # same as %$href{ ... } |
| 933 |
.Ve |
| 934 |
.PP |
| 935 |
As with postfix array, postfix value slice dereferencing \fIcan\fR be used |
| 936 |
in interpolating strings (double quotes or the \f(CW\*(C`qq\*(C'\fR operator), but only |
| 937 |
if the \f(CW\*(C`postderef_qq\*(C'\fR feature is enabled. |
| 938 |
.SS "Assigning to References" |
| 939 |
.IX Subsection "Assigning to References" |
| 940 |
Beginning in v5.22.0, the referencing operator can be assigned to. It |
| 941 |
performs an aliasing operation, so that the variable name referenced on the |
| 942 |
left-hand side becomes an alias for the thing referenced on the right-hand |
| 943 |
side: |
| 944 |
.PP |
| 945 |
.Vb 2 |
| 946 |
\& \e$x = \e$y; # $x and $y now point to the same scalar |
| 947 |
\& \e&foo = \e&bar; # foo() now means bar() |
| 948 |
.Ve |
| 949 |
.PP |
| 950 |
This syntax must be enabled with \f(CW\*(C`use feature \*(Aqrefaliasing\*(Aq\*(C'\fR. It is |
| 951 |
experimental, and will warn by default unless \f(CWno warnings |
| 952 |
\&\*(Aqexperimental::refaliasing\*(Aq\fR is in effect. |
| 953 |
.PP |
| 954 |
These forms may be assigned to, and cause the right-hand side to be |
| 955 |
evaluated in scalar context: |
| 956 |
.PP |
| 957 |
.Vb 10 |
| 958 |
\& \e$scalar |
| 959 |
\& \e@array |
| 960 |
\& \e%hash |
| 961 |
\& \e&sub |
| 962 |
\& \emy $scalar |
| 963 |
\& \emy @array |
| 964 |
\& \emy %hash |
| 965 |
\& \estate $scalar # or @array, etc. |
| 966 |
\& \eour $scalar # etc. |
| 967 |
\& \elocal $scalar # etc. |
| 968 |
\& \elocal our $scalar # etc. |
| 969 |
\& \e$some_array[$index] |
| 970 |
\& \e$some_hash{$key} |
| 971 |
\& \elocal $some_array[$index] |
| 972 |
\& \elocal $some_hash{$key} |
| 973 |
\& condition ? \e$this : \e$that[0] # etc. |
| 974 |
.Ve |
| 975 |
.PP |
| 976 |
Slicing operations and parentheses cause |
| 977 |
the right-hand side to be evaluated in |
| 978 |
list context: |
| 979 |
.PP |
| 980 |
.Vb 10 |
| 981 |
\& \e@array[5..7] |
| 982 |
\& (\e@array[5..7]) |
| 983 |
\& \e(@array[5..7]) |
| 984 |
\& \e@hash{\*(Aqfoo\*(Aq,\*(Aqbar\*(Aq} |
| 985 |
\& (\e@hash{\*(Aqfoo\*(Aq,\*(Aqbar\*(Aq}) |
| 986 |
\& \e(@hash{\*(Aqfoo\*(Aq,\*(Aqbar\*(Aq}) |
| 987 |
\& (\e$scalar) |
| 988 |
\& \e($scalar) |
| 989 |
\& \e(my $scalar) |
| 990 |
\& \emy($scalar) |
| 991 |
\& (\e@array) |
| 992 |
\& (\e%hash) |
| 993 |
\& (\e&sub) |
| 994 |
\& \e(&sub) |
| 995 |
\& \e($foo, @bar, %baz) |
| 996 |
\& (\e$foo, \e@bar, \e%baz) |
| 997 |
.Ve |
| 998 |
.PP |
| 999 |
Each element on the right-hand side must be a reference to a datum of the |
| 1000 |
right type. Parentheses immediately surrounding an array (and possibly |
| 1001 |
also \f(CW\*(C`my\*(C'\fR/\f(CW\*(C`state\*(C'\fR/\f(CW\*(C`our\*(C'\fR/\f(CW\*(C`local\*(C'\fR) will make each element of the array an |
| 1002 |
alias to the corresponding scalar referenced on the right-hand side: |
| 1003 |
.PP |
| 1004 |
.Vb 5 |
| 1005 |
\& \e(@x) = \e(@y); # @x and @y now have the same elements |
| 1006 |
\& \emy(@x) = \e(@y); # likewise |
| 1007 |
\& \e(my @x) = \e(@y); # likewise |
| 1008 |
\& push @x, 3; # but now @x has an extra element that @y lacks |
| 1009 |
\& \e(@x) = (\e$x, \e$y, \e$z); # @x now contains $x, $y, and $z |
| 1010 |
.Ve |
| 1011 |
.PP |
| 1012 |
Combining that form with \f(CW\*(C`local\*(C'\fR and putting parentheses immediately |
| 1013 |
around a hash are forbidden (because it is not clear what they should do): |
| 1014 |
.PP |
| 1015 |
.Vb 2 |
| 1016 |
\& \elocal(@array) = foo(); # WRONG |
| 1017 |
\& \e(%hash) = bar(); # WRONG |
| 1018 |
.Ve |
| 1019 |
.PP |
| 1020 |
Assignment to references and non-references may be combined in lists and |
| 1021 |
conditional ternary expressions, as long as the values on the right-hand |
| 1022 |
side are the right type for each element on the left, though this may make |
| 1023 |
for obfuscated code: |
| 1024 |
.PP |
| 1025 |
.Vb 4 |
| 1026 |
\& (my $tom, \emy $dick, \emy @harry) = (\e1, \e2, [1..3]); |
| 1027 |
\& # $tom is now \e1 |
| 1028 |
\& # $dick is now 2 (read\-only) |
| 1029 |
\& # @harry is (1,2,3) |
| 1030 |
\& |
| 1031 |
\& my $type = ref $thingy; |
| 1032 |
\& ($type ? $type eq \*(AqARRAY\*(Aq ? \e@foo : \e$bar : $baz) = $thingy; |
| 1033 |
.Ve |
| 1034 |
.PP |
| 1035 |
A reference assignment in list context returns a list of references to |
| 1036 |
each left-hand value. So for example |
| 1037 |
.PP |
| 1038 |
.Vb 1 |
| 1039 |
\& @b = ((\e$l1, \e$l2, \e(@a)) = (\e$r1, \e$r2, $\er3, \e$4)); |
| 1040 |
.Ve |
| 1041 |
.PP |
| 1042 |
is equivalent to |
| 1043 |
.PP |
| 1044 |
.Vb 2 |
| 1045 |
\& (\e$l1, \e$l2, \e(@a)) = (\e$r1, \e$r2, $\er3, \e$4); |
| 1046 |
\& @b = (\e$l1, \e$l2, \e$a[0], \e$a[1]); |
| 1047 |
.Ve |
| 1048 |
.PP |
| 1049 |
The \f(CW\*(C`foreach\*(C'\fR loop can also take a reference constructor for its loop |
| 1050 |
variable, though the syntax is limited to one of the following, with an |
| 1051 |
optional \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`state\*(C'\fR, or \f(CW\*(C`our\*(C'\fR after the backslash: |
| 1052 |
.PP |
| 1053 |
.Vb 4 |
| 1054 |
\& \e$s |
| 1055 |
\& \e@a |
| 1056 |
\& \e%h |
| 1057 |
\& \e&c |
| 1058 |
.Ve |
| 1059 |
.PP |
| 1060 |
No parentheses are permitted. This feature is particularly useful for |
| 1061 |
arrays-of-arrays, or arrays-of-hashes: |
| 1062 |
.PP |
| 1063 |
.Vb 3 |
| 1064 |
\& foreach \emy @a (@array_of_arrays) { |
| 1065 |
\& frobnicate($a[0], $a[\-1]); |
| 1066 |
\& } |
| 1067 |
\& |
| 1068 |
\& foreach \emy %h (@array_of_hashes) { |
| 1069 |
\& $h{gelastic}++ if $h{type} eq \*(Aqfunny\*(Aq; |
| 1070 |
\& } |
| 1071 |
.Ve |
| 1072 |
.PP |
| 1073 |
\&\fBCAVEAT:\fR Aliasing does not work correctly with closures. If you try to |
| 1074 |
alias lexical variables from an inner subroutine or \f(CW\*(C`eval\*(C'\fR, the aliasing |
| 1075 |
will only be visible within that inner sub, and will not affect the outer |
| 1076 |
subroutine where the variables are declared. This bizarre behavior is |
| 1077 |
subject to change. |
| 1078 |
.SS "Declaring a Reference to a Variable" |
| 1079 |
.IX Subsection "Declaring a Reference to a Variable" |
| 1080 |
Beginning in v5.26.0, the referencing operator can come after \f(CW\*(C`my\*(C'\fR, |
| 1081 |
\&\f(CW\*(C`state\*(C'\fR, \f(CW\*(C`our\*(C'\fR, or \f(CW\*(C`local\*(C'\fR. This syntax must be enabled with \f(CW\*(C`use |
| 1082 |
feature \*(Aqdeclared_refs\*(Aq\*(C'\fR. It is experimental, and will warn by default |
| 1083 |
unless \f(CW\*(C`no warnings \*(Aqexperimental::refaliasing\*(Aq\*(C'\fR is in effect. |
| 1084 |
.PP |
| 1085 |
This feature makes these: |
| 1086 |
.PP |
| 1087 |
.Vb 2 |
| 1088 |
\& my \e$x; |
| 1089 |
\& our \e$y; |
| 1090 |
.Ve |
| 1091 |
.PP |
| 1092 |
equivalent to: |
| 1093 |
.PP |
| 1094 |
.Vb 2 |
| 1095 |
\& \emy $x; |
| 1096 |
\& \eour $x; |
| 1097 |
.Ve |
| 1098 |
.PP |
| 1099 |
It is intended mainly for use in assignments to references (see |
| 1100 |
"Assigning to References", above). It also allows the backslash to be |
| 1101 |
used on just some items in a list of declared variables: |
| 1102 |
.PP |
| 1103 |
.Vb 1 |
| 1104 |
\& my ($foo, \e@bar, \e%baz); # equivalent to: my $foo, \emy(@bar, %baz); |
| 1105 |
.Ve |
| 1106 |
.SH "WARNING: Don't use references as hash keys" |
| 1107 |
.IX Xref "reference, string context reference, use as hash key" |
| 1108 |
.IX Header "WARNING: Don't use references as hash keys" |
| 1109 |
You may not (usefully) use a reference as the key to a hash. It will be |
| 1110 |
converted into a string: |
| 1111 |
.PP |
| 1112 |
.Vb 1 |
| 1113 |
\& $x{ \e$x } = $x; |
| 1114 |
.Ve |
| 1115 |
.PP |
| 1116 |
If you try to dereference the key, it won't do a hard dereference, and |
| 1117 |
you won't accomplish what you're attempting. You might want to do something |
| 1118 |
more like |
| 1119 |
.PP |
| 1120 |
.Vb 2 |
| 1121 |
\& $r = \e@a; |
| 1122 |
\& $x{ $r } = $r; |
| 1123 |
.Ve |
| 1124 |
.PP |
| 1125 |
And then at least you can use the \fBvalues()\fR, which will be |
| 1126 |
real refs, instead of the \fBkeys()\fR, which won't. |
| 1127 |
.PP |
| 1128 |
The standard Tie::RefHash module provides a convenient workaround to this. |
| 1129 |
.SH "SEE ALSO" |
| 1130 |
.IX Header "SEE ALSO" |
| 1131 |
Besides the obvious documents, source code can be instructive. |
| 1132 |
Some pathological examples of the use of references can be found |
| 1133 |
in the \fIt/op/ref.t\fR regression test in the Perl source directory. |
| 1134 |
.PP |
| 1135 |
See also perldsc and perllol for how to use references to create |
| 1136 |
complex data structures, and perlootut and perlobj |
| 1137 |
for how to use them to create objects. |