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