| 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 "PERLFAQ7 1" |
| 58 |
.TH PERLFAQ7 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 |
perlfaq7 \- General Perl Language Issues |
| 65 |
.SH VERSION |
| 66 |
.IX Header "VERSION" |
| 67 |
version 5.20240218 |
| 68 |
.SH DESCRIPTION |
| 69 |
.IX Header "DESCRIPTION" |
| 70 |
This section deals with general Perl language issues that don't |
| 71 |
clearly fit into any of the other sections. |
| 72 |
.SS "Can I get a BNF/yacc/RE for the Perl language?" |
| 73 |
.IX Subsection "Can I get a BNF/yacc/RE for the Perl language?" |
| 74 |
There is no BNF, but you can paw your way through the yacc grammar in |
| 75 |
perly.y in the source distribution if you're particularly brave. The |
| 76 |
grammar relies on very smart tokenizing code, so be prepared to |
| 77 |
venture into toke.c as well. |
| 78 |
.PP |
| 79 |
In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF. |
| 80 |
The work of parsing perl is distributed between yacc, the lexer, smoke |
| 81 |
and mirrors." |
| 82 |
.SS "What are all these $@%&* punctuation signs, and how do I know when to use them?" |
| 83 |
.IX Subsection "What are all these $@%&* punctuation signs, and how do I know when to use them?" |
| 84 |
They are type specifiers, as detailed in perldata: |
| 85 |
.PP |
| 86 |
.Vb 6 |
| 87 |
\& $ for scalar values (number, string or reference) |
| 88 |
\& @ for arrays |
| 89 |
\& % for hashes (associative arrays) |
| 90 |
\& & for subroutines (aka functions, procedures, methods) |
| 91 |
\& * for all types of that symbol name. In version 4 you used them like |
| 92 |
\& pointers, but in modern perls you can just use references. |
| 93 |
.Ve |
| 94 |
.PP |
| 95 |
There are a couple of other symbols that |
| 96 |
you're likely to encounter that aren't |
| 97 |
really type specifiers: |
| 98 |
.PP |
| 99 |
.Vb 2 |
| 100 |
\& <> are used for inputting a record from a filehandle. |
| 101 |
\& \e takes a reference to something. |
| 102 |
.Ve |
| 103 |
.PP |
| 104 |
Note that <FILE> is \fIneither\fR the type specifier for files |
| 105 |
nor the name of the handle. It is the \f(CW\*(C`<>\*(C'\fR operator applied |
| 106 |
to the handle FILE. It reads one line (well, record\-\-see |
| 107 |
"$/" in perlvar) from the handle FILE in scalar context, or \fIall\fR lines |
| 108 |
in list context. When performing open, close, or any other operation |
| 109 |
besides \f(CW\*(C`<>\*(C'\fR on files, or even when talking about the handle, do |
| 110 |
\&\fInot\fR use the brackets. These are correct: \f(CWeof(FH)\fR, \f(CW\*(C`seek(FH, 0, |
| 111 |
2)\*(C'\fR and "copying from STDIN to FILE". |
| 112 |
.SS "Do I always/never have to quote my strings or use semicolons and commas?" |
| 113 |
.IX Subsection "Do I always/never have to quote my strings or use semicolons and commas?" |
| 114 |
Normally, a bareword doesn't need to be quoted, but in most cases |
| 115 |
probably should be (and must be under \f(CW\*(C`use strict\*(C'\fR). But a hash key |
| 116 |
consisting of a simple word and the left-hand |
| 117 |
operand to the \f(CW\*(C`=>\*(C'\fR operator both |
| 118 |
count as though they were quoted: |
| 119 |
.PP |
| 120 |
.Vb 4 |
| 121 |
\& This is like this |
| 122 |
\& \-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\- |
| 123 |
\& $foo{line} $foo{\*(Aqline\*(Aq} |
| 124 |
\& bar => stuff \*(Aqbar\*(Aq => stuff |
| 125 |
.Ve |
| 126 |
.PP |
| 127 |
The final semicolon in a block is optional, as is the final comma in a |
| 128 |
list. Good style (see perlstyle) says to put them in except for |
| 129 |
one-liners: |
| 130 |
.PP |
| 131 |
.Vb 2 |
| 132 |
\& if ($whoops) { exit 1 } |
| 133 |
\& my @nums = (1, 2, 3); |
| 134 |
\& |
| 135 |
\& if ($whoops) { |
| 136 |
\& exit 1; |
| 137 |
\& } |
| 138 |
\& |
| 139 |
\& my @lines = ( |
| 140 |
\& "There Beren came from mountains cold", |
| 141 |
\& "And lost he wandered under leaves", |
| 142 |
\& ); |
| 143 |
.Ve |
| 144 |
.SS "How do I skip some return values?" |
| 145 |
.IX Subsection "How do I skip some return values?" |
| 146 |
One way is to treat the return values as a list and index into it: |
| 147 |
.PP |
| 148 |
.Vb 1 |
| 149 |
\& $dir = (getpwnam($user))[7]; |
| 150 |
.Ve |
| 151 |
.PP |
| 152 |
Another way is to use undef as an element on the left-hand-side: |
| 153 |
.PP |
| 154 |
.Vb 1 |
| 155 |
\& ($dev, $ino, undef, undef, $uid, $gid) = stat($file); |
| 156 |
.Ve |
| 157 |
.PP |
| 158 |
You can also use a list slice to select only the elements that |
| 159 |
you need: |
| 160 |
.PP |
| 161 |
.Vb 1 |
| 162 |
\& ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5]; |
| 163 |
.Ve |
| 164 |
.SS "How do I temporarily block warnings?" |
| 165 |
.IX Subsection "How do I temporarily block warnings?" |
| 166 |
If you are running Perl 5.6.0 or better, the \f(CW\*(C`use warnings\*(C'\fR pragma |
| 167 |
allows fine control of what warnings are produced. |
| 168 |
See perllexwarn for more details. |
| 169 |
.PP |
| 170 |
.Vb 4 |
| 171 |
\& { |
| 172 |
\& no warnings; # temporarily turn off warnings |
| 173 |
\& $x = $y + $z; # I know these might be undef |
| 174 |
\& } |
| 175 |
.Ve |
| 176 |
.PP |
| 177 |
Additionally, you can enable and disable categories of warnings. |
| 178 |
You turn off the categories you want to ignore and you can still |
| 179 |
get other categories of warnings. See perllexwarn for the |
| 180 |
complete details, including the category names and hierarchy. |
| 181 |
.PP |
| 182 |
.Vb 4 |
| 183 |
\& { |
| 184 |
\& no warnings \*(Aquninitialized\*(Aq; |
| 185 |
\& $x = $y + $z; |
| 186 |
\& } |
| 187 |
.Ve |
| 188 |
.PP |
| 189 |
If you have an older version of Perl, the \f(CW$^W\fR variable (documented |
| 190 |
in perlvar) controls runtime warnings for a block: |
| 191 |
.PP |
| 192 |
.Vb 4 |
| 193 |
\& { |
| 194 |
\& local $^W = 0; # temporarily turn off warnings |
| 195 |
\& $x = $y + $z; # I know these might be undef |
| 196 |
\& } |
| 197 |
.Ve |
| 198 |
.PP |
| 199 |
Note that like all the punctuation variables, you cannot currently |
| 200 |
use \fBmy()\fR on \f(CW$^W\fR, only \fBlocal()\fR. |
| 201 |
.SS "What's an extension?" |
| 202 |
.IX Subsection "What's an extension?" |
| 203 |
An extension is a way of calling compiled C code from Perl. Reading |
| 204 |
perlxstut is a good place to learn more about extensions. |
| 205 |
.SS "Why do Perl operators have different precedence than C operators?" |
| 206 |
.IX Subsection "Why do Perl operators have different precedence than C operators?" |
| 207 |
Actually, they don't. All C operators that Perl copies have the same |
| 208 |
precedence in Perl as they do in C. The problem is with operators that C |
| 209 |
doesn't have, especially functions that give a list context to everything |
| 210 |
on their right, eg. print, chmod, exec, and so on. Such functions are |
| 211 |
called "list operators" and appear as such in the precedence table in |
| 212 |
perlop. |
| 213 |
.PP |
| 214 |
A common mistake is to write: |
| 215 |
.PP |
| 216 |
.Vb 1 |
| 217 |
\& unlink $file || die "snafu"; |
| 218 |
.Ve |
| 219 |
.PP |
| 220 |
This gets interpreted as: |
| 221 |
.PP |
| 222 |
.Vb 1 |
| 223 |
\& unlink ($file || die "snafu"); |
| 224 |
.Ve |
| 225 |
.PP |
| 226 |
To avoid this problem, either put in extra parentheses or use the |
| 227 |
super low precedence \f(CW\*(C`or\*(C'\fR operator: |
| 228 |
.PP |
| 229 |
.Vb 2 |
| 230 |
\& (unlink $file) || die "snafu"; |
| 231 |
\& unlink $file or die "snafu"; |
| 232 |
.Ve |
| 233 |
.PP |
| 234 |
The "English" operators (\f(CW\*(C`and\*(C'\fR, \f(CW\*(C`or\*(C'\fR, \f(CW\*(C`xor\*(C'\fR, and \f(CW\*(C`not\*(C'\fR) |
| 235 |
deliberately have precedence lower than that of list operators for |
| 236 |
just such situations as the one above. |
| 237 |
.PP |
| 238 |
Another operator with surprising precedence is exponentiation. It |
| 239 |
binds more tightly even than unary minus, making \f(CW\*(C`\-2**2\*(C'\fR produce a |
| 240 |
negative four and not a positive one. It is also right-associating, meaning |
| 241 |
that \f(CW\*(C`2**3**2\*(C'\fR is two raised to the ninth power, not eight squared. |
| 242 |
.PP |
| 243 |
Although it has the same precedence as in C, Perl's \f(CW\*(C`?:\*(C'\fR operator |
| 244 |
produces an lvalue. This assigns \f(CW$x\fR to either \f(CW$if_true\fR or \f(CW$if_false\fR, depending |
| 245 |
on the trueness of \f(CW$maybe:\fR |
| 246 |
.PP |
| 247 |
.Vb 1 |
| 248 |
\& ($maybe ? $if_true : $if_false) = $x; |
| 249 |
.Ve |
| 250 |
.SS "How do I declare/create a structure?" |
| 251 |
.IX Subsection "How do I declare/create a structure?" |
| 252 |
In general, you don't "declare" a structure. Just use a (probably |
| 253 |
anonymous) hash reference. See perlref and perldsc for details. |
| 254 |
Here's an example: |
| 255 |
.PP |
| 256 |
.Vb 3 |
| 257 |
\& $person = {}; # new anonymous hash |
| 258 |
\& $person\->{AGE} = 24; # set field AGE to 24 |
| 259 |
\& $person\->{NAME} = "Nat"; # set field NAME to "Nat" |
| 260 |
.Ve |
| 261 |
.PP |
| 262 |
If you're looking for something a bit more rigorous, try perlootut. |
| 263 |
.SS "How do I create a module?" |
| 264 |
.IX Subsection "How do I create a module?" |
| 265 |
perlnewmod is a good place to start, ignore the bits |
| 266 |
about uploading to CPAN if you don't want to make your |
| 267 |
module publicly available. |
| 268 |
.PP |
| 269 |
ExtUtils::ModuleMaker and Module::Starter are also |
| 270 |
good places to start. Many CPAN authors now use Dist::Zilla |
| 271 |
to automate as much as possible. |
| 272 |
.PP |
| 273 |
Detailed documentation about modules can be found at: |
| 274 |
perlmod, perlmodlib, perlmodstyle. |
| 275 |
.PP |
| 276 |
If you need to include C code or C library interfaces |
| 277 |
use h2xs. h2xs will create the module distribution structure |
| 278 |
and the initial interface files. |
| 279 |
perlxs and perlxstut explain the details. |
| 280 |
.SS "How do I adopt or take over a module already on CPAN?" |
| 281 |
.IX Subsection "How do I adopt or take over a module already on CPAN?" |
| 282 |
Ask the current maintainer to make you a co-maintainer or |
| 283 |
transfer the module to you. |
| 284 |
.PP |
| 285 |
If you can not reach the author for some reason contact |
| 286 |
the PAUSE admins at [email protected] who may be able to help, |
| 287 |
but each case is treated separately. |
| 288 |
.IP \(bu 4 |
| 289 |
Get a login for the Perl Authors Upload Server (PAUSE) if you don't |
| 290 |
already have one: <http://pause.perl.org> |
| 291 |
.IP \(bu 4 |
| 292 |
Write to [email protected] explaining what you did to contact the |
| 293 |
current maintainer. The PAUSE admins will also try to reach the |
| 294 |
maintainer. |
| 295 |
.IP \(bu 4 |
| 296 |
Post a public message in a heavily trafficked site announcing your |
| 297 |
intention to take over the module. |
| 298 |
.IP \(bu 4 |
| 299 |
Wait a bit. The PAUSE admins don't want to act too quickly in case |
| 300 |
the current maintainer is on holiday. If there's no response to |
| 301 |
private communication or the public post, a PAUSE admin can transfer |
| 302 |
it to you. |
| 303 |
.SS "How do I create a class?" |
| 304 |
.IX Xref "class, creation package" |
| 305 |
.IX Subsection "How do I create a class?" |
| 306 |
(contributed by brian d foy) |
| 307 |
.PP |
| 308 |
In Perl, a class is just a package, and methods are just subroutines. |
| 309 |
Perl doesn't get more formal than that and lets you set up the package |
| 310 |
just the way that you like it (that is, it doesn't set up anything for |
| 311 |
you). |
| 312 |
.PP |
| 313 |
See also perlootut, a tutorial that covers class creation, and perlobj. |
| 314 |
.SS "How can I tell if a variable is tainted?" |
| 315 |
.IX Subsection "How can I tell if a variable is tainted?" |
| 316 |
You can use the \fBtainted()\fR function of the Scalar::Util module, available |
| 317 |
from CPAN (or included with Perl since release 5.8.0). |
| 318 |
See also "Laundering and Detecting Tainted Data" in perlsec. |
| 319 |
.SS "What's a closure?" |
| 320 |
.IX Subsection "What's a closure?" |
| 321 |
Closures are documented in perlref. |
| 322 |
.PP |
| 323 |
\&\fIClosure\fR is a computer science term with a precise but |
| 324 |
hard-to-explain meaning. Usually, closures are implemented in Perl as |
| 325 |
anonymous subroutines with lasting references to lexical variables |
| 326 |
outside their own scopes. These lexicals magically refer to the |
| 327 |
variables that were around when the subroutine was defined (deep |
| 328 |
binding). |
| 329 |
.PP |
| 330 |
Closures are most often used in programming languages where you can |
| 331 |
have the return value of a function be itself a function, as you can |
| 332 |
in Perl. Note that some languages provide anonymous functions but are |
| 333 |
not capable of providing proper closures: for example Python 2. For |
| 334 |
more information on closures, check out any textbook on functional |
| 335 |
programming. Scheme is a language that not only supports but |
| 336 |
encourages closures. |
| 337 |
.PP |
| 338 |
Here's a classic non-closure function-generating function: |
| 339 |
.PP |
| 340 |
.Vb 3 |
| 341 |
\& sub add_function_generator { |
| 342 |
\& return sub { shift() + shift() }; |
| 343 |
\& } |
| 344 |
\& |
| 345 |
\& my $add_sub = add_function_generator(); |
| 346 |
\& my $sum = $add_sub\->(4,5); # $sum is 9 now. |
| 347 |
.Ve |
| 348 |
.PP |
| 349 |
The anonymous subroutine returned by \fBadd_function_generator()\fR isn't |
| 350 |
technically a closure because it refers to no lexicals outside its own |
| 351 |
scope. Using a closure gives you a \fIfunction template\fR with some |
| 352 |
customization slots left out to be filled later. |
| 353 |
.PP |
| 354 |
Contrast this with the following \fBmake_adder()\fR function, in which the |
| 355 |
returned anonymous function contains a reference to a lexical variable |
| 356 |
outside the scope of that function itself. Such a reference requires |
| 357 |
that Perl return a proper closure, thus locking in for all time the |
| 358 |
value that the lexical had when the function was created. |
| 359 |
.PP |
| 360 |
.Vb 4 |
| 361 |
\& sub make_adder { |
| 362 |
\& my $addpiece = shift; |
| 363 |
\& return sub { shift() + $addpiece }; |
| 364 |
\& } |
| 365 |
\& |
| 366 |
\& my $f1 = make_adder(20); |
| 367 |
\& my $f2 = make_adder(555); |
| 368 |
.Ve |
| 369 |
.PP |
| 370 |
Now \f(CW$f1\->($n)\fR is always 20 plus whatever \f(CW$n\fR you pass in, whereas |
| 371 |
\&\f(CW$f2\->($n)\fR is always 555 plus whatever \f(CW$n\fR you pass in. The \f(CW$addpiece\fR |
| 372 |
in the closure sticks around. |
| 373 |
.PP |
| 374 |
Closures are often used for less esoteric purposes. For example, when |
| 375 |
you want to pass in a bit of code into a function: |
| 376 |
.PP |
| 377 |
.Vb 2 |
| 378 |
\& my $line; |
| 379 |
\& timeout( 30, sub { $line = <STDIN> } ); |
| 380 |
.Ve |
| 381 |
.PP |
| 382 |
If the code to execute had been passed in as a string, |
| 383 |
\&\f(CW\*(Aq$line = <STDIN>\*(Aq\fR, there would have been no way for the |
| 384 |
hypothetical \fBtimeout()\fR function to access the lexical variable |
| 385 |
\&\f(CW$line\fR back in its caller's scope. |
| 386 |
.PP |
| 387 |
Another use for a closure is to make a variable \fIprivate\fR to a |
| 388 |
named subroutine, e.g. a counter that gets initialized at creation |
| 389 |
time of the sub and can only be modified from within the sub. |
| 390 |
This is sometimes used with a BEGIN block in package files to make |
| 391 |
sure a variable doesn't get meddled with during the lifetime of the |
| 392 |
package: |
| 393 |
.PP |
| 394 |
.Vb 4 |
| 395 |
\& BEGIN { |
| 396 |
\& my $id = 0; |
| 397 |
\& sub next_id { ++$id } |
| 398 |
\& } |
| 399 |
.Ve |
| 400 |
.PP |
| 401 |
This is discussed in more detail in perlsub; see the entry on |
| 402 |
\&\fIPersistent Private Variables\fR. |
| 403 |
.SS "What is variable suicide and how can I prevent it?" |
| 404 |
.IX Subsection "What is variable suicide and how can I prevent it?" |
| 405 |
This problem was fixed in perl 5.004_05, so preventing it means upgrading |
| 406 |
your version of perl. ;) |
| 407 |
.PP |
| 408 |
Variable suicide is when you (temporarily or permanently) lose the value |
| 409 |
of a variable. It is caused by scoping through \fBmy()\fR and \fBlocal()\fR |
| 410 |
interacting with either closures or aliased \fBforeach()\fR iterator variables |
| 411 |
and subroutine arguments. It used to be easy to inadvertently lose a |
| 412 |
variable's value this way, but now it's much harder. Take this code: |
| 413 |
.PP |
| 414 |
.Vb 4 |
| 415 |
\& my $f = \*(Aqfoo\*(Aq; |
| 416 |
\& sub T { |
| 417 |
\& while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\en" } |
| 418 |
\& } |
| 419 |
\& |
| 420 |
\& T; |
| 421 |
\& print "Finally $f\en"; |
| 422 |
.Ve |
| 423 |
.PP |
| 424 |
If you are experiencing variable suicide, that \f(CW\*(C`my $f\*(C'\fR in the subroutine |
| 425 |
doesn't pick up a fresh copy of the \f(CW$f\fR whose value is \f(CW\*(Aqfoo\*(Aq\fR. The |
| 426 |
output shows that inside the subroutine the value of \f(CW$f\fR leaks through |
| 427 |
when it shouldn't, as in this output: |
| 428 |
.PP |
| 429 |
.Vb 4 |
| 430 |
\& foobar |
| 431 |
\& foobarbar |
| 432 |
\& foobarbarbar |
| 433 |
\& Finally foo |
| 434 |
.Ve |
| 435 |
.PP |
| 436 |
The \f(CW$f\fR that has "bar" added to it three times should be a new \f(CW$f\fR |
| 437 |
\&\f(CW\*(C`my $f\*(C'\fR should create a new lexical variable each time through the loop. |
| 438 |
The expected output is: |
| 439 |
.PP |
| 440 |
.Vb 4 |
| 441 |
\& foobar |
| 442 |
\& foobar |
| 443 |
\& foobar |
| 444 |
\& Finally foo |
| 445 |
.Ve |
| 446 |
.SS "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?" |
| 447 |
.IX Subsection "How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?" |
| 448 |
You need to pass references to these objects. See "Pass by |
| 449 |
Reference" in perlsub for this particular question, and perlref for |
| 450 |
information on references. |
| 451 |
.IP "Passing Variables and Functions" 4 |
| 452 |
.IX Item "Passing Variables and Functions" |
| 453 |
Regular variables and functions are quite easy to pass: just pass in a |
| 454 |
reference to an existing or anonymous variable or function: |
| 455 |
.Sp |
| 456 |
.Vb 1 |
| 457 |
\& func( \e$some_scalar ); |
| 458 |
\& |
| 459 |
\& func( \e@some_array ); |
| 460 |
\& func( [ 1 .. 10 ] ); |
| 461 |
\& |
| 462 |
\& func( \e%some_hash ); |
| 463 |
\& func( { this => 10, that => 20 } ); |
| 464 |
\& |
| 465 |
\& func( \e&some_func ); |
| 466 |
\& func( sub { $_[0] ** $_[1] } ); |
| 467 |
.Ve |
| 468 |
.IP "Passing Filehandles" 4 |
| 469 |
.IX Item "Passing Filehandles" |
| 470 |
As of Perl 5.6, you can represent filehandles with scalar variables |
| 471 |
which you treat as any other scalar. |
| 472 |
.Sp |
| 473 |
.Vb 2 |
| 474 |
\& open my $fh, $filename or die "Cannot open $filename! $!"; |
| 475 |
\& func( $fh ); |
| 476 |
\& |
| 477 |
\& sub func { |
| 478 |
\& my $passed_fh = shift; |
| 479 |
\& |
| 480 |
\& my $line = <$passed_fh>; |
| 481 |
\& } |
| 482 |
.Ve |
| 483 |
.Sp |
| 484 |
Before Perl 5.6, you had to use the \f(CW*FH\fR or \f(CW\*(C`\e*FH\*(C'\fR notations. |
| 485 |
These are "typeglobs"\-\-see "Typeglobs and Filehandles" in perldata |
| 486 |
and especially "Pass by Reference" in perlsub for more information. |
| 487 |
.IP "Passing Regexes" 4 |
| 488 |
.IX Item "Passing Regexes" |
| 489 |
Here's an example of how to pass in a string and a regular expression |
| 490 |
for it to match against. You construct the pattern with the \f(CW\*(C`qr//\*(C'\fR |
| 491 |
operator: |
| 492 |
.Sp |
| 493 |
.Vb 6 |
| 494 |
\& sub compare { |
| 495 |
\& my ($val1, $regex) = @_; |
| 496 |
\& my $retval = $val1 =~ /$regex/; |
| 497 |
\& return $retval; |
| 498 |
\& } |
| 499 |
\& $match = compare("old McDonald", qr/d.*D/i); |
| 500 |
.Ve |
| 501 |
.IP "Passing Methods" 4 |
| 502 |
.IX Item "Passing Methods" |
| 503 |
To pass an object method into a subroutine, you can do this: |
| 504 |
.Sp |
| 505 |
.Vb 7 |
| 506 |
\& call_a_lot(10, $some_obj, "methname") |
| 507 |
\& sub call_a_lot { |
| 508 |
\& my ($count, $widget, $trick) = @_; |
| 509 |
\& for (my $i = 0; $i < $count; $i++) { |
| 510 |
\& $widget\->$trick(); |
| 511 |
\& } |
| 512 |
\& } |
| 513 |
.Ve |
| 514 |
.Sp |
| 515 |
Or, you can use a closure to bundle up the object, its |
| 516 |
method call, and arguments: |
| 517 |
.Sp |
| 518 |
.Vb 6 |
| 519 |
\& my $whatnot = sub { $some_obj\->obfuscate(@args) }; |
| 520 |
\& func($whatnot); |
| 521 |
\& sub func { |
| 522 |
\& my $code = shift; |
| 523 |
\& &$code(); |
| 524 |
\& } |
| 525 |
.Ve |
| 526 |
.Sp |
| 527 |
You could also investigate the \fBcan()\fR method in the UNIVERSAL class |
| 528 |
(part of the standard perl distribution). |
| 529 |
.SS "How do I create a static variable?" |
| 530 |
.IX Subsection "How do I create a static variable?" |
| 531 |
(contributed by brian d foy) |
| 532 |
.PP |
| 533 |
In Perl 5.10, declare the variable with \f(CW\*(C`state\*(C'\fR. The \f(CW\*(C`state\*(C'\fR |
| 534 |
declaration creates the lexical variable that persists between calls |
| 535 |
to the subroutine: |
| 536 |
.PP |
| 537 |
.Vb 1 |
| 538 |
\& sub counter { state $count = 1; $count++ } |
| 539 |
.Ve |
| 540 |
.PP |
| 541 |
You can fake a static variable by using a lexical variable which goes |
| 542 |
out of scope. In this example, you define the subroutine \f(CW\*(C`counter\*(C'\fR, and |
| 543 |
it uses the lexical variable \f(CW$count\fR. Since you wrap this in a BEGIN |
| 544 |
block, \f(CW$count\fR is defined at compile-time, but also goes out of |
| 545 |
scope at the end of the BEGIN block. The BEGIN block also ensures that |
| 546 |
the subroutine and the value it uses is defined at compile-time so the |
| 547 |
subroutine is ready to use just like any other subroutine, and you can |
| 548 |
put this code in the same place as other subroutines in the program |
| 549 |
text (i.e. at the end of the code, typically). The subroutine |
| 550 |
\&\f(CW\*(C`counter\*(C'\fR still has a reference to the data, and is the only way you |
| 551 |
can access the value (and each time you do, you increment the value). |
| 552 |
The data in chunk of memory defined by \f(CW$count\fR is private to |
| 553 |
\&\f(CW\*(C`counter\*(C'\fR. |
| 554 |
.PP |
| 555 |
.Vb 4 |
| 556 |
\& BEGIN { |
| 557 |
\& my $count = 1; |
| 558 |
\& sub counter { $count++ } |
| 559 |
\& } |
| 560 |
\& |
| 561 |
\& my $start = counter(); |
| 562 |
\& |
| 563 |
\& .... # code that calls counter(); |
| 564 |
\& |
| 565 |
\& my $end = counter(); |
| 566 |
.Ve |
| 567 |
.PP |
| 568 |
In the previous example, you created a function-private variable |
| 569 |
because only one function remembered its reference. You could define |
| 570 |
multiple functions while the variable is in scope, and each function |
| 571 |
can share the "private" variable. It's not really "static" because you |
| 572 |
can access it outside the function while the lexical variable is in |
| 573 |
scope, and even create references to it. In this example, |
| 574 |
\&\f(CW\*(C`increment_count\*(C'\fR and \f(CW\*(C`return_count\*(C'\fR share the variable. One |
| 575 |
function adds to the value and the other simply returns the value. |
| 576 |
They can both access \f(CW$count\fR, and since it has gone out of scope, |
| 577 |
there is no other way to access it. |
| 578 |
.PP |
| 579 |
.Vb 5 |
| 580 |
\& BEGIN { |
| 581 |
\& my $count = 1; |
| 582 |
\& sub increment_count { $count++ } |
| 583 |
\& sub return_count { $count } |
| 584 |
\& } |
| 585 |
.Ve |
| 586 |
.PP |
| 587 |
To declare a file-private variable, you still use a lexical variable. |
| 588 |
A file is also a scope, so a lexical variable defined in the file |
| 589 |
cannot be seen from any other file. |
| 590 |
.PP |
| 591 |
See "Persistent Private Variables" in perlsub for more information. |
| 592 |
The discussion of closures in perlref may help you even though we |
| 593 |
did not use anonymous subroutines in this answer. See |
| 594 |
"Persistent Private Variables" in perlsub for details. |
| 595 |
.SS "What's the difference between dynamic and lexical (static) scoping? Between \fBlocal()\fP and \fBmy()\fP?" |
| 596 |
.IX Subsection "What's the difference between dynamic and lexical (static) scoping? Between local() and my()?" |
| 597 |
\&\f(CWlocal($x)\fR saves away the old value of the global variable \f(CW$x\fR |
| 598 |
and assigns a new value for the duration of the subroutine \fIwhich is |
| 599 |
visible in other functions called from that subroutine\fR. This is done |
| 600 |
at run-time, so is called dynamic scoping. \fBlocal()\fR always affects global |
| 601 |
variables, also called package variables or dynamic variables. |
| 602 |
.PP |
| 603 |
\&\f(CWmy($x)\fR creates a new variable that is only visible in the current |
| 604 |
subroutine. This is done at compile-time, so it is called lexical or |
| 605 |
static scoping. \fBmy()\fR always affects private variables, also called |
| 606 |
lexical variables or (improperly) static(ly scoped) variables. |
| 607 |
.PP |
| 608 |
For instance: |
| 609 |
.PP |
| 610 |
.Vb 3 |
| 611 |
\& sub visible { |
| 612 |
\& print "var has value $var\en"; |
| 613 |
\& } |
| 614 |
\& |
| 615 |
\& sub dynamic { |
| 616 |
\& local $var = \*(Aqlocal\*(Aq; # new temporary value for the still\-global |
| 617 |
\& visible(); # variable called $var |
| 618 |
\& } |
| 619 |
\& |
| 620 |
\& sub lexical { |
| 621 |
\& my $var = \*(Aqprivate\*(Aq; # new private variable, $var |
| 622 |
\& visible(); # (invisible outside of sub scope) |
| 623 |
\& } |
| 624 |
\& |
| 625 |
\& $var = \*(Aqglobal\*(Aq; |
| 626 |
\& |
| 627 |
\& visible(); # prints global |
| 628 |
\& dynamic(); # prints local |
| 629 |
\& lexical(); # prints global |
| 630 |
.Ve |
| 631 |
.PP |
| 632 |
Notice how at no point does the value "private" get printed. That's |
| 633 |
because \f(CW$var\fR only has that value within the block of the \fBlexical()\fR |
| 634 |
function, and it is hidden from the called subroutine. |
| 635 |
.PP |
| 636 |
In summary, \fBlocal()\fR doesn't make what you think of as private, local |
| 637 |
variables. It gives a global variable a temporary value. \fBmy()\fR is |
| 638 |
what you're looking for if you want private variables. |
| 639 |
.PP |
| 640 |
See "Private Variables via \fBmy()\fR" in perlsub and |
| 641 |
"Temporary Values via \fBlocal()\fR" in perlsub for excruciating details. |
| 642 |
.SS "How can I access a dynamic variable while a similarly named lexical is in scope?" |
| 643 |
.IX Subsection "How can I access a dynamic variable while a similarly named lexical is in scope?" |
| 644 |
If you know your package, you can just mention it explicitly, as in |
| 645 |
\&\f(CW$Some_Pack::var\fR. Note that the notation \f(CW$::var\fR is \fBnot\fR the dynamic \f(CW$var\fR |
| 646 |
in the current package, but rather the one in the "main" package, as |
| 647 |
though you had written \f(CW$main::var\fR. |
| 648 |
.PP |
| 649 |
.Vb 3 |
| 650 |
\& use vars \*(Aq$var\*(Aq; |
| 651 |
\& local $var = "global"; |
| 652 |
\& my $var = "lexical"; |
| 653 |
\& |
| 654 |
\& print "lexical is $var\en"; |
| 655 |
\& print "global is $main::var\en"; |
| 656 |
.Ve |
| 657 |
.PP |
| 658 |
Alternatively you can use the compiler directive \fBour()\fR to bring a |
| 659 |
dynamic variable into the current lexical scope. |
| 660 |
.PP |
| 661 |
.Vb 2 |
| 662 |
\& require 5.006; # our() did not exist before 5.6 |
| 663 |
\& use vars \*(Aq$var\*(Aq; |
| 664 |
\& |
| 665 |
\& local $var = "global"; |
| 666 |
\& my $var = "lexical"; |
| 667 |
\& |
| 668 |
\& print "lexical is $var\en"; |
| 669 |
\& |
| 670 |
\& { |
| 671 |
\& our $var; |
| 672 |
\& print "global is $var\en"; |
| 673 |
\& } |
| 674 |
.Ve |
| 675 |
.SS "What's the difference between deep and shallow binding?" |
| 676 |
.IX Subsection "What's the difference between deep and shallow binding?" |
| 677 |
In deep binding, lexical variables mentioned in anonymous subroutines |
| 678 |
are the same ones that were in scope when the subroutine was created. |
| 679 |
In shallow binding, they are whichever variables with the same names |
| 680 |
happen to be in scope when the subroutine is called. Perl always uses |
| 681 |
deep binding of lexical variables (i.e., those created with \fBmy()\fR). |
| 682 |
However, dynamic variables (aka global, local, or package variables) |
| 683 |
are effectively shallowly bound. Consider this just one more reason |
| 684 |
not to use them. See the answer to "What's a closure?". |
| 685 |
.SS "Why doesn't ""my($foo) = <$fh>;"" work right?" |
| 686 |
.IX Subsection "Why doesn't ""my($foo) = <$fh>;"" work right?" |
| 687 |
\&\f(CWmy()\fR and \f(CWlocal()\fR give list context to the right hand side |
| 688 |
of \f(CW\*(C`=\*(C'\fR. The <$fh> read operation, like so many of Perl's |
| 689 |
functions and operators, can tell which context it was called in and |
| 690 |
behaves appropriately. In general, the \fBscalar()\fR function can help. |
| 691 |
This function does nothing to the data itself (contrary to popular myth) |
| 692 |
but rather tells its argument to behave in whatever its scalar fashion is. |
| 693 |
If that function doesn't have a defined scalar behavior, this of course |
| 694 |
doesn't help you (such as with \fBsort()\fR). |
| 695 |
.PP |
| 696 |
To enforce scalar context in this particular case, however, you need |
| 697 |
merely omit the parentheses: |
| 698 |
.PP |
| 699 |
.Vb 3 |
| 700 |
\& local($foo) = <$fh>; # WRONG |
| 701 |
\& local($foo) = scalar(<$fh>); # ok |
| 702 |
\& local $foo = <$fh>; # right |
| 703 |
.Ve |
| 704 |
.PP |
| 705 |
You should probably be using lexical variables anyway, although the |
| 706 |
issue is the same here: |
| 707 |
.PP |
| 708 |
.Vb 2 |
| 709 |
\& my($foo) = <$fh>; # WRONG |
| 710 |
\& my $foo = <$fh>; # right |
| 711 |
.Ve |
| 712 |
.SS "How do I redefine a builtin function, operator, or method?" |
| 713 |
.IX Subsection "How do I redefine a builtin function, operator, or method?" |
| 714 |
Why do you want to do that? :\-) |
| 715 |
.PP |
| 716 |
If you want to override a predefined function, such as \fBopen()\fR, |
| 717 |
then you'll have to import the new definition from a different |
| 718 |
module. See "Overriding Built-in Functions" in perlsub. |
| 719 |
.PP |
| 720 |
If you want to overload a Perl operator, such as \f(CW\*(C`+\*(C'\fR or \f(CW\*(C`**\*(C'\fR, |
| 721 |
then you'll want to use the \f(CW\*(C`use overload\*(C'\fR pragma, documented |
| 722 |
in overload. |
| 723 |
.PP |
| 724 |
If you're talking about obscuring method calls in parent classes, |
| 725 |
see "Overriding methods and method resolution" in perlootut. |
| 726 |
.SS "What's the difference between calling a function as &foo and \fBfoo()\fP?" |
| 727 |
.IX Subsection "What's the difference between calling a function as &foo and foo()?" |
| 728 |
(contributed by brian d foy) |
| 729 |
.PP |
| 730 |
Calling a subroutine as \f(CW&foo\fR with no trailing parentheses ignores |
| 731 |
the prototype of \f(CW\*(C`foo\*(C'\fR and passes it the current value of the argument |
| 732 |
list, \f(CW@_\fR. Here's an example; the \f(CW\*(C`bar\*(C'\fR subroutine calls \f(CW&foo\fR, |
| 733 |
which prints its arguments list: |
| 734 |
.PP |
| 735 |
.Vb 1 |
| 736 |
\& sub foo { print "Args in foo are: @_\en"; } |
| 737 |
\& |
| 738 |
\& sub bar { &foo; } |
| 739 |
\& |
| 740 |
\& bar( "a", "b", "c" ); |
| 741 |
.Ve |
| 742 |
.PP |
| 743 |
When you call \f(CW\*(C`bar\*(C'\fR with arguments, you see that \f(CW\*(C`foo\*(C'\fR got the same \f(CW@_\fR: |
| 744 |
.PP |
| 745 |
.Vb 1 |
| 746 |
\& Args in foo are: a b c |
| 747 |
.Ve |
| 748 |
.PP |
| 749 |
Calling the subroutine with trailing parentheses, with or without arguments, |
| 750 |
does not use the current \f(CW@_\fR. Changing the example to put parentheses after |
| 751 |
the call to \f(CW\*(C`foo\*(C'\fR changes the program: |
| 752 |
.PP |
| 753 |
.Vb 1 |
| 754 |
\& sub foo { print "Args in foo are: @_\en"; } |
| 755 |
\& |
| 756 |
\& sub bar { &foo(); } |
| 757 |
\& |
| 758 |
\& bar( "a", "b", "c" ); |
| 759 |
.Ve |
| 760 |
.PP |
| 761 |
Now the output shows that \f(CW\*(C`foo\*(C'\fR doesn't get the \f(CW@_\fR from its caller. |
| 762 |
.PP |
| 763 |
.Vb 1 |
| 764 |
\& Args in foo are: |
| 765 |
.Ve |
| 766 |
.PP |
| 767 |
However, using \f(CW\*(C`&\*(C'\fR in the call still overrides the prototype of \f(CW\*(C`foo\*(C'\fR if |
| 768 |
present: |
| 769 |
.PP |
| 770 |
.Vb 1 |
| 771 |
\& sub foo ($$$) { print "Args infoo are: @_\en"; } |
| 772 |
\& |
| 773 |
\& sub bar_1 { &foo; } |
| 774 |
\& sub bar_2 { &foo(); } |
| 775 |
\& sub bar_3 { foo( $_[0], $_[1], $_[2] ); } |
| 776 |
\& # sub bar_4 { foo(); } |
| 777 |
\& # bar_4 doesn\*(Aqt compile: "Not enough arguments for main::foo at ..." |
| 778 |
\& |
| 779 |
\& bar_1( "a", "b", "c" ); |
| 780 |
\& # Args in foo are: a b c |
| 781 |
\& |
| 782 |
\& bar_2( "a", "b", "c" ); |
| 783 |
\& # Args in foo are: |
| 784 |
\& |
| 785 |
\& bar_3( "a", "b", "c" ); |
| 786 |
\& # Args in foo are: a b c |
| 787 |
.Ve |
| 788 |
.PP |
| 789 |
The main use of the \f(CW@_\fR pass-through feature is to write subroutines |
| 790 |
whose main job it is to call other subroutines for you. For further |
| 791 |
details, see perlsub. |
| 792 |
.SS "How do I create a switch or case statement?" |
| 793 |
.IX Subsection "How do I create a switch or case statement?" |
| 794 |
There is a given/when statement in Perl, but it is experimental and |
| 795 |
will be removed in Perl 5.42. See perlsyn for more details. |
| 796 |
.PP |
| 797 |
The general answer is to use a CPAN module such as Switch::Plain: |
| 798 |
.PP |
| 799 |
.Vb 6 |
| 800 |
\& use Switch::Plain; |
| 801 |
\& sswitch($variable_holding_a_string) { |
| 802 |
\& case \*(Aqfirst\*(Aq: { } |
| 803 |
\& case \*(Aqsecond\*(Aq: { } |
| 804 |
\& default: { } |
| 805 |
\& } |
| 806 |
.Ve |
| 807 |
.PP |
| 808 |
or for more complicated comparisons, \f(CW\*(C`if\-elsif\-else\*(C'\fR: |
| 809 |
.PP |
| 810 |
.Vb 6 |
| 811 |
\& for ($variable_to_test) { |
| 812 |
\& if (/pat1/) { } # do something |
| 813 |
\& elsif (/pat2/) { } # do something else |
| 814 |
\& elsif (/pat3/) { } # do something else |
| 815 |
\& else { } # default |
| 816 |
\& } |
| 817 |
.Ve |
| 818 |
.PP |
| 819 |
Here's a simple example of a switch based on pattern matching, |
| 820 |
lined up in a way to make it look more like a switch statement. |
| 821 |
We'll do a multiway conditional based on the type of reference stored |
| 822 |
in \f(CW$whatchamacallit:\fR |
| 823 |
.PP |
| 824 |
.Vb 1 |
| 825 |
\& SWITCH: for (ref $whatchamacallit) { |
| 826 |
\& |
| 827 |
\& /^$/ && die "not a reference"; |
| 828 |
\& |
| 829 |
\& /SCALAR/ && do { |
| 830 |
\& print_scalar($$ref); |
| 831 |
\& last SWITCH; |
| 832 |
\& }; |
| 833 |
\& |
| 834 |
\& /ARRAY/ && do { |
| 835 |
\& print_array(@$ref); |
| 836 |
\& last SWITCH; |
| 837 |
\& }; |
| 838 |
\& |
| 839 |
\& /HASH/ && do { |
| 840 |
\& print_hash(%$ref); |
| 841 |
\& last SWITCH; |
| 842 |
\& }; |
| 843 |
\& |
| 844 |
\& /CODE/ && do { |
| 845 |
\& warn "can\*(Aqt print function ref"; |
| 846 |
\& last SWITCH; |
| 847 |
\& }; |
| 848 |
\& |
| 849 |
\& # DEFAULT |
| 850 |
\& |
| 851 |
\& warn "User defined type skipped"; |
| 852 |
\& |
| 853 |
\& } |
| 854 |
.Ve |
| 855 |
.PP |
| 856 |
See perlsyn for other examples in this style. |
| 857 |
.PP |
| 858 |
Sometimes you should change the positions of the constant and the variable. |
| 859 |
For example, let's say you wanted to test which of many answers you were |
| 860 |
given, but in a case-insensitive way that also allows abbreviations. |
| 861 |
You can use the following technique if the strings all start with |
| 862 |
different characters or if you want to arrange the matches so that |
| 863 |
one takes precedence over another, as \f(CW"SEND"\fR has precedence over |
| 864 |
\&\f(CW"STOP"\fR here: |
| 865 |
.PP |
| 866 |
.Vb 6 |
| 867 |
\& chomp($answer = <>); |
| 868 |
\& if ("SEND" =~ /^\eQ$answer/i) { print "Action is send\en" } |
| 869 |
\& elsif ("STOP" =~ /^\eQ$answer/i) { print "Action is stop\en" } |
| 870 |
\& elsif ("ABORT" =~ /^\eQ$answer/i) { print "Action is abort\en" } |
| 871 |
\& elsif ("LIST" =~ /^\eQ$answer/i) { print "Action is list\en" } |
| 872 |
\& elsif ("EDIT" =~ /^\eQ$answer/i) { print "Action is edit\en" } |
| 873 |
.Ve |
| 874 |
.PP |
| 875 |
A totally different approach is to create a hash of function references. |
| 876 |
.PP |
| 877 |
.Vb 6 |
| 878 |
\& my %commands = ( |
| 879 |
\& "happy" => \e&joy, |
| 880 |
\& "sad", => \e&sullen, |
| 881 |
\& "done" => sub { die "See ya!" }, |
| 882 |
\& "mad" => \e&angry, |
| 883 |
\& ); |
| 884 |
\& |
| 885 |
\& print "How are you? "; |
| 886 |
\& chomp($string = <STDIN>); |
| 887 |
\& if ($commands{$string}) { |
| 888 |
\& $commands{$string}\->(); |
| 889 |
\& } else { |
| 890 |
\& print "No such command: $string\en"; |
| 891 |
\& } |
| 892 |
.Ve |
| 893 |
.PP |
| 894 |
Starting from Perl 5.8, a source filter module, \f(CW\*(C`Switch\*(C'\fR, can also be |
| 895 |
used to get switch and case. Its use is now discouraged, because it's |
| 896 |
not fully compatible with the native switch of Perl 5.10, and because, |
| 897 |
as it's implemented as a source filter, it doesn't always work as intended |
| 898 |
when complex syntax is involved. |
| 899 |
.SS "How can I catch accesses to undefined variables, functions, or methods?" |
| 900 |
.IX Subsection "How can I catch accesses to undefined variables, functions, or methods?" |
| 901 |
The AUTOLOAD method, discussed in "Autoloading" in perlsub lets you capture |
| 902 |
calls to undefined functions and methods. |
| 903 |
.PP |
| 904 |
When it comes to undefined variables that would trigger a warning |
| 905 |
under \f(CW\*(C`use warnings\*(C'\fR, you can promote the warning to an error. |
| 906 |
.PP |
| 907 |
.Vb 1 |
| 908 |
\& use warnings FATAL => qw(uninitialized); |
| 909 |
.Ve |
| 910 |
.SS "Why can't a method included in this same file be found?" |
| 911 |
.IX Subsection "Why can't a method included in this same file be found?" |
| 912 |
Some possible reasons: your inheritance is getting confused, you've |
| 913 |
misspelled the method name, or the object is of the wrong type. Check |
| 914 |
out perlootut for details about any of the above cases. You may |
| 915 |
also use \f(CW\*(C`print ref($object)\*(C'\fR to find out the class \f(CW$object\fR was |
| 916 |
blessed into. |
| 917 |
.PP |
| 918 |
Another possible reason for problems is that you've used the |
| 919 |
indirect object syntax (eg, \f(CW\*(C`find Guru "Samy"\*(C'\fR) on a class name |
| 920 |
before Perl has seen that such a package exists. It's wisest to make |
| 921 |
sure your packages are all defined before you start using them, which |
| 922 |
will be taken care of if you use the \f(CW\*(C`use\*(C'\fR statement instead of |
| 923 |
\&\f(CW\*(C`require\*(C'\fR. If not, make sure to use arrow notation (eg., |
| 924 |
\&\f(CW\*(C`Guru\->find("Samy")\*(C'\fR) instead. Object notation is explained in |
| 925 |
perlobj. |
| 926 |
.PP |
| 927 |
Make sure to read about creating modules in perlmod and |
| 928 |
the perils of indirect objects in "Method Invocation" in perlobj. |
| 929 |
.SS "How can I find out my current or calling package?" |
| 930 |
.IX Subsection "How can I find out my current or calling package?" |
| 931 |
(contributed by brian d foy) |
| 932 |
.PP |
| 933 |
To find the package you are currently in, use the special literal |
| 934 |
\&\f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR, as documented in perldata. You can only use the |
| 935 |
special literals as separate tokens, so you can't interpolate them |
| 936 |
into strings like you can with variables: |
| 937 |
.PP |
| 938 |
.Vb 2 |
| 939 |
\& my $current_package = _\|_PACKAGE_\|_; |
| 940 |
\& print "I am in package $current_package\en"; |
| 941 |
.Ve |
| 942 |
.PP |
| 943 |
If you want to find the package calling your code, perhaps to give better |
| 944 |
diagnostics as Carp does, use the \f(CW\*(C`caller\*(C'\fR built-in: |
| 945 |
.PP |
| 946 |
.Vb 3 |
| 947 |
\& sub foo { |
| 948 |
\& my @args = ...; |
| 949 |
\& my( $package, $filename, $line ) = caller; |
| 950 |
\& |
| 951 |
\& print "I was called from package $package\en"; |
| 952 |
\& ); |
| 953 |
.Ve |
| 954 |
.PP |
| 955 |
By default, your program starts in package \f(CW\*(C`main\*(C'\fR, so you will |
| 956 |
always be in some package. |
| 957 |
.PP |
| 958 |
This is different from finding out the package an object is blessed |
| 959 |
into, which might not be the current package. For that, use \f(CW\*(C`blessed\*(C'\fR |
| 960 |
from Scalar::Util, part of the Standard Library since Perl 5.8: |
| 961 |
.PP |
| 962 |
.Vb 2 |
| 963 |
\& use Scalar::Util qw(blessed); |
| 964 |
\& my $object_package = blessed( $object ); |
| 965 |
.Ve |
| 966 |
.PP |
| 967 |
Most of the time, you shouldn't care what package an object is blessed |
| 968 |
into, however, as long as it claims to inherit from that class: |
| 969 |
.PP |
| 970 |
.Vb 1 |
| 971 |
\& my $is_right_class = eval { $object\->isa( $package ) }; # true or false |
| 972 |
.Ve |
| 973 |
.PP |
| 974 |
And, with Perl 5.10 and later, you don't have to check for an |
| 975 |
inheritance to see if the object can handle a role. For that, you can |
| 976 |
use \f(CW\*(C`DOES\*(C'\fR, which comes from \f(CW\*(C`UNIVERSAL\*(C'\fR: |
| 977 |
.PP |
| 978 |
.Vb 1 |
| 979 |
\& my $class_does_it = eval { $object\->DOES( $role ) }; # true or false |
| 980 |
.Ve |
| 981 |
.PP |
| 982 |
You can safely replace \f(CW\*(C`isa\*(C'\fR with \f(CW\*(C`DOES\*(C'\fR (although the converse is not true). |
| 983 |
.SS "How can I comment out a large block of Perl code?" |
| 984 |
.IX Subsection "How can I comment out a large block of Perl code?" |
| 985 |
(contributed by brian d foy) |
| 986 |
.PP |
| 987 |
The quick-and-dirty way to comment out more than one line of Perl is |
| 988 |
to surround those lines with Pod directives. You have to put these |
| 989 |
directives at the beginning of the line and somewhere where Perl |
| 990 |
expects a new statement (so not in the middle of statements like the \f(CW\*(C`#\*(C'\fR |
| 991 |
comments). You end the comment with \f(CW\*(C`=cut\*(C'\fR, ending the Pod section: |
| 992 |
.PP |
| 993 |
.Vb 1 |
| 994 |
\& =pod |
| 995 |
\& |
| 996 |
\& my $object = NotGonnaHappen\->new(); |
| 997 |
\& |
| 998 |
\& ignored_sub(); |
| 999 |
\& |
| 1000 |
\& $wont_be_assigned = 37; |
| 1001 |
\& |
| 1002 |
\& =cut |
| 1003 |
.Ve |
| 1004 |
.PP |
| 1005 |
The quick-and-dirty method only works well when you don't plan to |
| 1006 |
leave the commented code in the source. If a Pod parser comes along, |
| 1007 |
your multiline comment is going to show up in the Pod translation. |
| 1008 |
A better way hides it from Pod parsers as well. |
| 1009 |
.PP |
| 1010 |
The \f(CW\*(C`=begin\*(C'\fR directive can mark a section for a particular purpose. |
| 1011 |
If the Pod parser doesn't want to handle it, it just ignores it. Label |
| 1012 |
the comments with \f(CW\*(C`comment\*(C'\fR. End the comment using \f(CW\*(C`=end\*(C'\fR with the |
| 1013 |
same label. You still need the \f(CW\*(C`=cut\*(C'\fR to go back to Perl code from |
| 1014 |
the Pod comment: |
| 1015 |
.PP |
| 1016 |
.Vb 1 |
| 1017 |
\& =begin comment |
| 1018 |
\& |
| 1019 |
\& my $object = NotGonnaHappen\->new(); |
| 1020 |
\& |
| 1021 |
\& ignored_sub(); |
| 1022 |
\& |
| 1023 |
\& $wont_be_assigned = 37; |
| 1024 |
\& |
| 1025 |
\& =end comment |
| 1026 |
\& |
| 1027 |
\& =cut |
| 1028 |
.Ve |
| 1029 |
.PP |
| 1030 |
For more information on Pod, check out perlpod and perlpodspec. |
| 1031 |
.SS "How do I clear a package?" |
| 1032 |
.IX Subsection "How do I clear a package?" |
| 1033 |
Use this code, provided by Mark-Jason Dominus: |
| 1034 |
.PP |
| 1035 |
.Vb 10 |
| 1036 |
\& sub scrub_package { |
| 1037 |
\& no strict \*(Aqrefs\*(Aq; |
| 1038 |
\& my $pack = shift; |
| 1039 |
\& die "Shouldn\*(Aqt delete main package" |
| 1040 |
\& if $pack eq "" || $pack eq "main"; |
| 1041 |
\& my $stash = *{$pack . \*(Aq::\*(Aq}{HASH}; |
| 1042 |
\& my $name; |
| 1043 |
\& foreach $name (keys %$stash) { |
| 1044 |
\& my $fullname = $pack . \*(Aq::\*(Aq . $name; |
| 1045 |
\& # Get rid of everything with that name. |
| 1046 |
\& undef $$fullname; |
| 1047 |
\& undef @$fullname; |
| 1048 |
\& undef %$fullname; |
| 1049 |
\& undef &$fullname; |
| 1050 |
\& undef *$fullname; |
| 1051 |
\& } |
| 1052 |
\& } |
| 1053 |
.Ve |
| 1054 |
.PP |
| 1055 |
Or, if you're using a recent release of Perl, you can |
| 1056 |
just use the \fBSymbol::delete_package()\fR function instead. |
| 1057 |
.SS "How can I use a variable as a variable name?" |
| 1058 |
.IX Subsection "How can I use a variable as a variable name?" |
| 1059 |
Beginners often think they want to have a variable contain the name |
| 1060 |
of a variable. |
| 1061 |
.PP |
| 1062 |
.Vb 3 |
| 1063 |
\& $fred = 23; |
| 1064 |
\& $varname = "fred"; |
| 1065 |
\& ++$$varname; # $fred now 24 |
| 1066 |
.Ve |
| 1067 |
.PP |
| 1068 |
This works \fIsometimes\fR, but it is a very bad idea for two reasons. |
| 1069 |
.PP |
| 1070 |
The first reason is that this technique \fIonly works on global |
| 1071 |
variables\fR. That means that if \f(CW$fred\fR is a lexical variable created |
| 1072 |
with \fBmy()\fR in the above example, the code wouldn't work at all: you'd |
| 1073 |
accidentally access the global and skip right over the private lexical |
| 1074 |
altogether. Global variables are bad because they can easily collide |
| 1075 |
accidentally and in general make for non-scalable and confusing code. |
| 1076 |
.PP |
| 1077 |
Symbolic references are forbidden under the \f(CW\*(C`use strict\*(C'\fR pragma. |
| 1078 |
They are not true references and consequently are not reference-counted |
| 1079 |
or garbage-collected. |
| 1080 |
.PP |
| 1081 |
The other reason why using a variable to hold the name of another |
| 1082 |
variable is a bad idea is that the question often stems from a lack of |
| 1083 |
understanding of Perl data structures, particularly hashes. By using |
| 1084 |
symbolic references, you are just using the package's symbol-table hash |
| 1085 |
(like \f(CW%main::\fR) instead of a user-defined hash. The solution is to |
| 1086 |
use your own hash or a real reference instead. |
| 1087 |
.PP |
| 1088 |
.Vb 3 |
| 1089 |
\& $USER_VARS{"fred"} = 23; |
| 1090 |
\& my $varname = "fred"; |
| 1091 |
\& $USER_VARS{$varname}++; # not $$varname++ |
| 1092 |
.Ve |
| 1093 |
.PP |
| 1094 |
There we're using the \f(CW%USER_VARS\fR hash instead of symbolic references. |
| 1095 |
Sometimes this comes up in reading strings from the user with variable |
| 1096 |
references and wanting to expand them to the values of your perl |
| 1097 |
program's variables. This is also a bad idea because it conflates the |
| 1098 |
program-addressable namespace and the user-addressable one. Instead of |
| 1099 |
reading a string and expanding it to the actual contents of your program's |
| 1100 |
own variables: |
| 1101 |
.PP |
| 1102 |
.Vb 2 |
| 1103 |
\& $str = \*(Aqthis has a $fred and $barney in it\*(Aq; |
| 1104 |
\& $str =~ s/(\e$\ew+)/$1/eeg; # need double eval |
| 1105 |
.Ve |
| 1106 |
.PP |
| 1107 |
it would be better to keep a hash around like \f(CW%USER_VARS\fR and have |
| 1108 |
variable references actually refer to entries in that hash: |
| 1109 |
.PP |
| 1110 |
.Vb 1 |
| 1111 |
\& $str =~ s/\e$(\ew+)/$USER_VARS{$1}/g; # no /e here at all |
| 1112 |
.Ve |
| 1113 |
.PP |
| 1114 |
That's faster, cleaner, and safer than the previous approach. Of course, |
| 1115 |
you don't need to use a dollar sign. You could use your own scheme to |
| 1116 |
make it less confusing, like bracketed percent symbols, etc. |
| 1117 |
.PP |
| 1118 |
.Vb 2 |
| 1119 |
\& $str = \*(Aqthis has a %fred% and %barney% in it\*(Aq; |
| 1120 |
\& $str =~ s/%(\ew+)%/$USER_VARS{$1}/g; # no /e here at all |
| 1121 |
.Ve |
| 1122 |
.PP |
| 1123 |
Another reason that folks sometimes think they want a variable to |
| 1124 |
contain the name of a variable is that they don't know how to build |
| 1125 |
proper data structures using hashes. For example, let's say they |
| 1126 |
wanted two hashes in their program: \f(CW%fred\fR and \f(CW%barney\fR, and that they |
| 1127 |
wanted to use another scalar variable to refer to those by name. |
| 1128 |
.PP |
| 1129 |
.Vb 2 |
| 1130 |
\& $name = "fred"; |
| 1131 |
\& $$name{WIFE} = "wilma"; # set %fred |
| 1132 |
\& |
| 1133 |
\& $name = "barney"; |
| 1134 |
\& $$name{WIFE} = "betty"; # set %barney |
| 1135 |
.Ve |
| 1136 |
.PP |
| 1137 |
This is still a symbolic reference, and is still saddled with the |
| 1138 |
problems enumerated above. It would be far better to write: |
| 1139 |
.PP |
| 1140 |
.Vb 2 |
| 1141 |
\& $folks{"fred"}{WIFE} = "wilma"; |
| 1142 |
\& $folks{"barney"}{WIFE} = "betty"; |
| 1143 |
.Ve |
| 1144 |
.PP |
| 1145 |
And just use a multilevel hash to start with. |
| 1146 |
.PP |
| 1147 |
The only times that you absolutely \fImust\fR use symbolic references are |
| 1148 |
when you really must refer to the symbol table. This may be because it's |
| 1149 |
something that one can't take a real reference to, such as a format name. |
| 1150 |
Doing so may also be important for method calls, since these always go |
| 1151 |
through the symbol table for resolution. |
| 1152 |
.PP |
| 1153 |
In those cases, you would turn off \f(CW\*(C`strict \*(Aqrefs\*(Aq\*(C'\fR temporarily so you |
| 1154 |
can play around with the symbol table. For example: |
| 1155 |
.PP |
| 1156 |
.Vb 5 |
| 1157 |
\& @colors = qw(red blue green yellow orange purple violet); |
| 1158 |
\& for my $name (@colors) { |
| 1159 |
\& no strict \*(Aqrefs\*(Aq; # renege for the block |
| 1160 |
\& *$name = sub { "<FONT COLOR=\*(Aq$name\*(Aq>@_</FONT>" }; |
| 1161 |
\& } |
| 1162 |
.Ve |
| 1163 |
.PP |
| 1164 |
All those functions (\fBred()\fR, \fBblue()\fR, \fBgreen()\fR, etc.) appear to be separate, |
| 1165 |
but the real code in the closure actually was compiled only once. |
| 1166 |
.PP |
| 1167 |
So, sometimes you might want to use symbolic references to manipulate |
| 1168 |
the symbol table directly. This doesn't matter for formats, handles, and |
| 1169 |
subroutines, because they are always global\-\-you can't use \fBmy()\fR on them. |
| 1170 |
For scalars, arrays, and hashes, though\-\-and usually for subroutines\-\- |
| 1171 |
you probably only want to use hard references. |
| 1172 |
.SS "What does ""bad interpreter"" mean?" |
| 1173 |
.IX Subsection "What does ""bad interpreter"" mean?" |
| 1174 |
(contributed by brian d foy) |
| 1175 |
.PP |
| 1176 |
The "bad interpreter" message comes from the shell, not perl. The |
| 1177 |
actual message may vary depending on your platform, shell, and locale |
| 1178 |
settings. |
| 1179 |
.PP |
| 1180 |
If you see "bad interpreter \- no such file or directory", the first |
| 1181 |
line in your perl script (the "shebang" line) does not contain the |
| 1182 |
right path to perl (or any other program capable of running scripts). |
| 1183 |
Sometimes this happens when you move the script from one machine to |
| 1184 |
another and each machine has a different path to perl\-\-/usr/bin/perl |
| 1185 |
versus /usr/local/bin/perl for instance. It may also indicate |
| 1186 |
that the source machine has CRLF line terminators and the |
| 1187 |
destination machine has LF only: the shell tries to find |
| 1188 |
/usr/bin/perl<CR>, but can't. |
| 1189 |
.PP |
| 1190 |
If you see "bad interpreter: Permission denied", you need to make your |
| 1191 |
script executable. |
| 1192 |
.PP |
| 1193 |
In either case, you should still be able to run the scripts with perl |
| 1194 |
explicitly: |
| 1195 |
.PP |
| 1196 |
.Vb 1 |
| 1197 |
\& % perl script.pl |
| 1198 |
.Ve |
| 1199 |
.PP |
| 1200 |
If you get a message like "perl: command not found", perl is not in |
| 1201 |
your PATH, which might also mean that the location of perl is not |
| 1202 |
where you expect it so you need to adjust your shebang line. |
| 1203 |
.SS "Do I need to recompile XS modules when there is a change in the C library?" |
| 1204 |
.IX Subsection "Do I need to recompile XS modules when there is a change in the C library?" |
| 1205 |
(contributed by Alex Beamish) |
| 1206 |
.PP |
| 1207 |
If the new version of the C library is ABI-compatible (that's Application |
| 1208 |
Binary Interface compatible) with the version you're upgrading from, and if the |
| 1209 |
shared library version didn't change, no re-compilation should be necessary. |
| 1210 |
.SH "AUTHOR AND COPYRIGHT" |
| 1211 |
.IX Header "AUTHOR AND COPYRIGHT" |
| 1212 |
Copyright (c) 1997\-2013 Tom Christiansen, Nathan Torkington, and |
| 1213 |
other authors as noted. All rights reserved. |
| 1214 |
.PP |
| 1215 |
This documentation is free; you can redistribute it and/or modify it |
| 1216 |
under the same terms as Perl itself. |
| 1217 |
.PP |
| 1218 |
Irrespective of its distribution, all code examples in this file |
| 1219 |
are hereby placed into the public domain. You are permitted and |
| 1220 |
encouraged to use this code in your own programs for fun |
| 1221 |
or for profit as you see fit. A simple comment in the code giving |
| 1222 |
credit would be courteous but is not required. |