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