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