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