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