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