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