1PERLFAQ7(1)            Perl Programmers Reference Guide            PERLFAQ7(1)
2
3
4

NAME

6       perlfaq7 - General Perl Language Issues
7

DESCRIPTION

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