Debian Codegraph @

upstream/opensuse-tumbleweed/man1/perlfaq7.1

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