-x should be C<-x>, reported by Gerben Wierda.
[p5sagit/p5-mst-13.2.git] / pod / perlfaq7.pod
CommitLineData
68dc0745 1=head1 NAME
2
c8db1d39 3perlfaq7 - Perl Language Issues ($Revision: 1.21 $, $Date: 1998/06/22 15:20:07 $)
68dc0745 4
5=head1 DESCRIPTION
6
7This section deals with general Perl language issues that don't
8clearly fit into any of the other sections.
9
10=head2 Can I get a BNF/yacc/RE for the Perl language?
11
c8db1d39 12There is no BNF, but you can paw your way through the yacc grammar in
13perly.y in the source distribution if you're particularly brave. The
14grammar relies on very smart tokenizing code, so be prepared to
15venture into toke.c as well.
16
17In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF.
18The work of parsing perl is distributed between yacc, the lexer, smoke
19and mirrors."
68dc0745 20
21=head2 What are all these $@%* punctuation signs, and how do I know when to use them?
22
23They are type specifiers, as detailed in L<perldata>:
24
25 $ for scalar values (number, string or reference)
26 @ for arrays
27 % for hashes (associative arrays)
28 * for all types of that symbol name. In version 4 you used them like
29 pointers, but in modern perls you can just use references.
30
31While there are a few places where you don't actually need these type
32specifiers, you should always use them.
33
34A couple of others that you're likely to encounter that aren't
35really type specifiers are:
36
37 <> are used for inputting a record from a filehandle.
38 \ takes a reference to something.
39
40Note that E<lt>FILEE<gt> is I<neither> the type specifier for files
41nor the name of the handle. It is the C<E<lt>E<gt>> operator applied
42to the handle FILE. It reads one line (well, record - see
43L<perlvar/$/>) from the handle FILE in scalar context, or I<all> lines
44in list context. When performing open, close, or any other operation
45besides C<E<lt>E<gt>> on files, or even talking about the handle, do
46I<not> use the brackets. These are correct: C<eof(FH)>, C<seek(FH, 0,
472)> and "copying from STDIN to FILE".
48
49=head2 Do I always/never have to quote my strings or use semicolons and commas?
50
51Normally, a bareword doesn't need to be quoted, but in most cases
52probably should be (and must be under C<use strict>). But a hash key
53consisting of a simple word (that isn't the name of a defined
54subroutine) and the left-hand operand to the C<=E<gt>> operator both
55count as though they were quoted:
56
57 This is like this
58 ------------ ---------------
59 $foo{line} $foo{"line"}
60 bar => stuff "bar" => stuff
61
62The final semicolon in a block is optional, as is the final comma in a
63list. Good style (see L<perlstyle>) says to put them in except for
64one-liners:
65
66 if ($whoops) { exit 1 }
67 @nums = (1, 2, 3);
68
69 if ($whoops) {
70 exit 1;
71 }
72 @lines = (
73 "There Beren came from mountains cold",
74 "And lost he wandered under leaves",
75 );
76
77=head2 How do I skip some return values?
78
79One way is to treat the return values as a list and index into it:
80
81 $dir = (getpwnam($user))[7];
82
83Another way is to use undef as an element on the left-hand-side:
84
85 ($dev, $ino, undef, undef, $uid, $gid) = stat($file);
86
87=head2 How do I temporarily block warnings?
88
89The C<$^W> variable (documented in L<perlvar>) controls
90runtime warnings for a block:
91
92 {
93 local $^W = 0; # temporarily turn off warnings
94 $a = $b + $c; # I know these might be undef
95 }
96
97Note that like all the punctuation variables, you cannot currently
98use my() on C<$^W>, only local().
99
100A new C<use warnings> pragma is in the works to provide finer control
101over all this. The curious should check the perl5-porters mailing list
102archives for details.
103
104=head2 What's an extension?
105
106A way of calling compiled C code from Perl. Reading L<perlxstut>
107is a good place to learn more about extensions.
108
109=head2 Why do Perl operators have different precedence than C operators?
110
111Actually, they don't. All C operators that Perl copies have the same
112precedence in Perl as they do in C. The problem is with operators that C
113doesn't have, especially functions that give a list context to everything
114on their right, eg print, chmod, exec, and so on. Such functions are
115called "list operators" and appear as such in the precedence table in
116L<perlop>.
117
118A common mistake is to write:
119
120 unlink $file || die "snafu";
121
122This gets interpreted as:
123
124 unlink ($file || die "snafu");
125
126To avoid this problem, either put in extra parentheses or use the
127super low precedence C<or> operator:
128
129 (unlink $file) || die "snafu";
130 unlink $file or die "snafu";
131
132The "English" operators (C<and>, C<or>, C<xor>, and C<not>)
133deliberately have precedence lower than that of list operators for
134just such situations as the one above.
135
136Another operator with surprising precedence is exponentiation. It
137binds more tightly even than unary minus, making C<-2**2> product a
138negative not a positive four. It is also right-associating, meaning
139that C<2**3**2> is two raised to the ninth power, not eight squared.
140
c8db1d39 141Although it has the same precedence as in C, Perl's C<?:> operator
142produces an lvalue. This assigns $x to either $a or $b, depending
143on the trueness of $maybe:
144
145 ($maybe ? $a : $b) = $x;
146
68dc0745 147=head2 How do I declare/create a structure?
148
149In general, you don't "declare" a structure. Just use a (probably
150anonymous) hash reference. See L<perlref> and L<perldsc> for details.
151Here's an example:
152
153 $person = {}; # new anonymous hash
154 $person->{AGE} = 24; # set field AGE to 24
155 $person->{NAME} = "Nat"; # set field NAME to "Nat"
156
157If you're looking for something a bit more rigorous, try L<perltoot>.
158
159=head2 How do I create a module?
160
161A module is a package that lives in a file of the same name. For
162example, the Hello::There module would live in Hello/There.pm. For
163details, read L<perlmod>. You'll also find L<Exporter> helpful. If
164you're writing a C or mixed-language module with both C and Perl, then
165you should study L<perlxstut>.
166
167Here's a convenient template you might wish you use when starting your
168own module. Make sure to change the names appropriately.
169
170 package Some::Module; # assumes Some/Module.pm
171
172 use strict;
173
174 BEGIN {
175 use Exporter ();
176 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
177
178 ## set the version for version checking; uncomment to use
179 ## $VERSION = 1.00;
180
181 # if using RCS/CVS, this next line may be preferred,
182 # but beware two-digit versions.
c8db1d39 183 $VERSION = do{my@r=q$Revision: 1.21 $=~/\d+/g;sprintf '%d.'.'%02d'x$#r,@r};
68dc0745 184
185 @ISA = qw(Exporter);
186 @EXPORT = qw(&func1 &func2 &func3);
187 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
188
189 # your exported package globals go here,
190 # as well as any optionally exported functions
191 @EXPORT_OK = qw($Var1 %Hashit);
192 }
193 use vars @EXPORT_OK;
194
195 # non-exported package globals go here
196 use vars qw( @more $stuff );
197
198 # initialize package globals, first exported ones
199 $Var1 = '';
200 %Hashit = ();
201
202 # then the others (which are still accessible as $Some::Module::stuff)
203 $stuff = '';
204 @more = ();
205
206 # all file-scoped lexicals must be created before
207 # the functions below that use them.
208
209 # file-private lexicals go here
210 my $priv_var = '';
211 my %secret_hash = ();
212
213 # here's a file-private function as a closure,
214 # callable as &$priv_func; it cannot be prototyped.
215 my $priv_func = sub {
216 # stuff goes here.
217 };
218
219 # make all your functions, whether exported or not;
220 # remember to put something interesting in the {} stubs
221 sub func1 {} # no prototype
222 sub func2() {} # proto'd void
223 sub func3($$) {} # proto'd to 2 scalars
224
225 # this one isn't exported, but could be called!
226 sub func4(\%) {} # proto'd to 1 hash ref
227
228 END { } # module clean-up code here (global destructor)
229
230 1; # modules must return true
231
232=head2 How do I create a class?
233
234See L<perltoot> for an introduction to classes and objects, as well as
235L<perlobj> and L<perlbot>.
236
237=head2 How can I tell if a variable is tainted?
238
239See L<perlsec/"Laundering and Detecting Tainted Data">. Here's an
240example (which doesn't use any system calls, because the kill()
241is given no processes to signal):
242
243 sub is_tainted {
244 return ! eval { join('',@_), kill 0; 1; };
245 }
246
247This is not C<-w> clean, however. There is no C<-w> clean way to
248detect taintedness - take this as a hint that you should untaint
249all possibly-tainted data.
250
251=head2 What's a closure?
252
253Closures are documented in L<perlref>.
254
255I<Closure> is a computer science term with a precise but
256hard-to-explain meaning. Closures are implemented in Perl as anonymous
257subroutines with lasting references to lexical variables outside their
258own scopes. These lexicals magically refer to the variables that were
259around when the subroutine was defined (deep binding).
260
261Closures make sense in any programming language where you can have the
262return value of a function be itself a function, as you can in Perl.
263Note that some languages provide anonymous functions but are not
264capable of providing proper closures; the Python language, for
265example. For more information on closures, check out any textbook on
266functional programming. Scheme is a language that not only supports
267but encourages closures.
268
269Here's a classic function-generating function:
270
271 sub add_function_generator {
272 return sub { shift + shift };
273 }
274
275 $add_sub = add_function_generator();
c8db1d39 276 $sum = $add_sub->(4,5); # $sum is 9 now.
68dc0745 277
278The closure works as a I<function template> with some customization
279slots left out to be filled later. The anonymous subroutine returned
280by add_function_generator() isn't technically a closure because it
281refers to no lexicals outside its own scope.
282
283Contrast this with the following make_adder() function, in which the
284returned anonymous function contains a reference to a lexical variable
285outside the scope of that function itself. Such a reference requires
286that Perl return a proper closure, thus locking in for all time the
287value that the lexical had when the function was created.
288
289 sub make_adder {
290 my $addpiece = shift;
291 return sub { shift + $addpiece };
292 }
293
294 $f1 = make_adder(20);
295 $f2 = make_adder(555);
296
297Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas
298C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece
299in the closure sticks around.
300
301Closures are often used for less esoteric purposes. For example, when
302you want to pass in a bit of code into a function:
303
304 my $line;
305 timeout( 30, sub { $line = <STDIN> } );
306
307If the code to execute had been passed in as a string, C<'$line =
308E<lt>STDINE<gt>'>, there would have been no way for the hypothetical
309timeout() function to access the lexical variable $line back in its
310caller's scope.
311
46fc3d4c 312=head2 What is variable suicide and how can I prevent it?
313
314Variable suicide is when you (temporarily or permanently) lose the
315value of a variable. It is caused by scoping through my() and local()
316interacting with either closures or aliased foreach() interator
317variables and subroutine arguments. It used to be easy to
318inadvertently lose a variable's value this way, but now it's much
319harder. Take this code:
320
321 my $f = "foo";
322 sub T {
323 while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
324 }
325 T;
326 print "Finally $f\n";
327
328The $f that has "bar" added to it three times should be a new C<$f>
329(C<my $f> should create a new local variable each time through the
330loop). It isn't, however. This is a bug, and will be fixed.
331
68dc0745 332=head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regexp}?
333
334With the exception of regexps, you need to pass references to these
335objects. See L<perlsub/"Pass by Reference"> for this particular
336question, and L<perlref> for information on references.
337
338=over 4
339
340=item Passing Variables and Functions
341
342Regular variables and functions are quite easy: just pass in a
343reference to an existing or anonymous variable or function:
344
345 func( \$some_scalar );
346
92c2ed05 347 func( \$some_array );
68dc0745 348 func( [ 1 .. 10 ] );
349
350 func( \%some_hash );
351 func( { this => 10, that => 20 } );
352
353 func( \&some_func );
354 func( sub { $_[0] ** $_[1] } );
355
356=item Passing Filehandles
357
c8db1d39 358To pass filehandles to subroutines, use the C<*FH> or C<\*FH> notations.
359These are "typeglobs" - see L<perldata/"Typeglobs and Filehandles">
360and especially L<perlsub/"Pass by Reference"> for more information.
361
362Here's an excerpt:
363
364If you're passing around filehandles, you could usually just use the bare
365typeglob, like *STDOUT, but typeglobs references would be better because
366they'll still work properly under C<use strict 'refs'>. For example:
68dc0745 367
c8db1d39 368 splutter(\*STDOUT);
369 sub splutter {
370 my $fh = shift;
371 print $fh "her um well a hmmm\n";
372 }
373
374 $rec = get_rec(\*STDIN);
375 sub get_rec {
376 my $fh = shift;
377 return scalar <$fh>;
378 }
379
380If you're planning on generating new filehandles, you could do this:
381
382 sub openit {
383 my $name = shift;
384 local *FH;
385 return open (FH, $path) ? *FH : undef;
386 }
387 $fh = openit('< /etc/motd');
388 print <$fh>;
68dc0745 389
390=item Passing Regexps
391
392To pass regexps around, you'll need to either use one of the highly
393experimental regular expression modules from CPAN (Nick Ing-Simmons's
46fc3d4c 394Regexp or Ilya Zakharevich's Devel::Regexp), pass around strings
395and use an exception-trapping eval, or else be be very, very clever.
396Here's an example of how to pass in a string to be regexp compared:
68dc0745 397
398 sub compare($$) {
399 my ($val1, $regexp) = @_;
400 my $retval = eval { $val =~ /$regexp/ };
401 die if $@;
402 return $retval;
403 }
404
405 $match = compare("old McDonald", q/d.*D/);
406
407Make sure you never say something like this:
408
409 return eval "\$val =~ /$regexp/"; # WRONG
410
411or someone can sneak shell escapes into the regexp due to the double
412interpolation of the eval and the double-quoted string. For example:
413
414 $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger';
415
416 eval "\$string =~ /$pattern_of_evil/";
417
418Those preferring to be very, very clever might see the O'Reilly book,
419I<Mastering Regular Expressions>, by Jeffrey Friedl. Page 273's
420Build_MatchMany_Function() is particularly interesting. A complete
421citation of this book is given in L<perlfaq2>.
422
423=item Passing Methods
424
425To pass an object method into a subroutine, you can do this:
426
427 call_a_lot(10, $some_obj, "methname")
428 sub call_a_lot {
429 my ($count, $widget, $trick) = @_;
430 for (my $i = 0; $i < $count; $i++) {
431 $widget->$trick();
432 }
433 }
434
c8db1d39 435Or you can use a closure to bundle up the object and its method call
68dc0745 436and arguments:
437
438 my $whatnot = sub { $some_obj->obfuscate(@args) };
439 func($whatnot);
440 sub func {
441 my $code = shift;
442 &$code();
443 }
444
445You could also investigate the can() method in the UNIVERSAL class
446(part of the standard perl distribution).
447
448=back
449
450=head2 How do I create a static variable?
451
452As with most things in Perl, TMTOWTDI. What is a "static variable" in
453other languages could be either a function-private variable (visible
454only within a single function, retaining its value between calls to
455that function), or a file-private variable (visible only to functions
456within the file it was declared in) in Perl.
457
458Here's code to implement a function-private variable:
459
460 BEGIN {
461 my $counter = 42;
462 sub prev_counter { return --$counter }
463 sub next_counter { return $counter++ }
464 }
465
466Now prev_counter() and next_counter() share a private variable $counter
467that was initialized at compile time.
468
469To declare a file-private variable, you'll still use a my(), putting
470it at the outer scope level at the top of the file. Assume this is in
471file Pax.pm:
472
473 package Pax;
474 my $started = scalar(localtime(time()));
475
476 sub begun { return $started }
477
478When C<use Pax> or C<require Pax> loads this module, the variable will
479be initialized. It won't get garbage-collected the way most variables
480going out of scope do, because the begun() function cares about it,
481but no one else can get it. It is not called $Pax::started because
482its scope is unrelated to the package. It's scoped to the file. You
483could conceivably have several packages in that same file all
484accessing the same private variable, but another file with the same
485package couldn't get to it.
486
c8db1d39 487See L<perlsub/"Peristent Private Variables"> for details.
488
68dc0745 489=head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()?
490
491C<local($x)> saves away the old value of the global variable C<$x>,
492and assigns a new value for the duration of the subroutine, I<which is
493visible in other functions called from that subroutine>. This is done
494at run-time, so is called dynamic scoping. local() always affects global
495variables, also called package variables or dynamic variables.
496
497C<my($x)> creates a new variable that is only visible in the current
498subroutine. This is done at compile-time, so is called lexical or
499static scoping. my() always affects private variables, also called
500lexical variables or (improperly) static(ly scoped) variables.
501
502For instance:
503
504 sub visible {
505 print "var has value $var\n";
506 }
507
508 sub dynamic {
509 local $var = 'local'; # new temporary value for the still-global
510 visible(); # variable called $var
511 }
512
513 sub lexical {
514 my $var = 'private'; # new private variable, $var
515 visible(); # (invisible outside of sub scope)
516 }
517
518 $var = 'global';
519
520 visible(); # prints global
521 dynamic(); # prints local
522 lexical(); # prints global
523
524Notice how at no point does the value "private" get printed. That's
525because $var only has that value within the block of the lexical()
526function, and it is hidden from called subroutine.
527
528In summary, local() doesn't make what you think of as private, local
529variables. It gives a global variable a temporary value. my() is
530what you're looking for if you want private variables.
531
c8db1d39 532See L<perlsub/"Private Variables via my()"> and L<perlsub/"Temporary
533Values via local()"> for excruciating details.
68dc0745 534
535=head2 How can I access a dynamic variable while a similarly named lexical is in scope?
536
537You can do this via symbolic references, provided you haven't set
538C<use strict "refs">. So instead of $var, use C<${'var'}>.
539
540 local $var = "global";
541 my $var = "lexical";
542
543 print "lexical is $var\n";
544
545 no strict 'refs';
546 print "global is ${'var'}\n";
547
548If you know your package, you can just mention it explicitly, as in
549$Some_Pack::var. Note that the notation $::var is I<not> the dynamic
550$var in the current package, but rather the one in the C<main>
551package, as though you had written $main::var. Specifying the package
552directly makes you hard-code its name, but it executes faster and
553avoids running afoul of C<use strict "refs">.
554
555=head2 What's the difference between deep and shallow binding?
556
557In deep binding, lexical variables mentioned in anonymous subroutines
558are the same ones that were in scope when the subroutine was created.
559In shallow binding, they are whichever variables with the same names
560happen to be in scope when the subroutine is called. Perl always uses
561deep binding of lexical variables (i.e., those created with my()).
562However, dynamic variables (aka global, local, or package variables)
563are effectively shallowly bound. Consider this just one more reason
564not to use them. See the answer to L<"What's a closure?">.
565
c8db1d39 566=head2 Why doesn't "my($foo) = <FILE>;" work right?
68dc0745 567
c8db1d39 568C<my()> and C<local()> give list context to the right hand side
569of C<=>. The E<lt>FHE<gt> read operation, like so many of Perl's
570functions and operators, can tell which context it was called in and
571behaves appropriately. In general, the scalar() function can help.
572This function does nothing to the data itself (contrary to popular myth)
573but rather tells its argument to behave in whatever its scalar fashion is.
574If that function doesn't have a defined scalar behavior, this of course
575doesn't help you (such as with sort()).
68dc0745 576
577To enforce scalar context in this particular case, however, you need
578merely omit the parentheses:
579
580 local($foo) = <FILE>; # WRONG
581 local($foo) = scalar(<FILE>); # ok
582 local $foo = <FILE>; # right
583
584You should probably be using lexical variables anyway, although the
585issue is the same here:
586
587 my($foo) = <FILE>; # WRONG
588 my $foo = <FILE>; # right
589
54310121 590=head2 How do I redefine a builtin function, operator, or method?
68dc0745 591
592Why do you want to do that? :-)
593
594If you want to override a predefined function, such as open(),
595then you'll have to import the new definition from a different
596module. See L<perlsub/"Overriding Builtin Functions">. There's
46fc3d4c 597also an example in L<perltoot/"Class::Template">.
68dc0745 598
599If you want to overload a Perl operator, such as C<+> or C<**>,
600then you'll want to use the C<use overload> pragma, documented
601in L<overload>.
602
603If you're talking about obscuring method calls in parent classes,
604see L<perltoot/"Overridden Methods">.
605
606=head2 What's the difference between calling a function as &foo and foo()?
607
608When you call a function as C<&foo>, you allow that function access to
609your current @_ values, and you by-pass prototypes. That means that
610the function doesn't get an empty @_, it gets yours! While not
611strictly speaking a bug (it's documented that way in L<perlsub>), it
612would be hard to consider this a feature in most cases.
613
c8db1d39 614When you call your function as C<&foo()>, then you I<do> get a new @_,
68dc0745 615but prototyping is still circumvented.
616
617Normally, you want to call a function using C<foo()>. You may only
618omit the parentheses if the function is already known to the compiler
619because it already saw the definition (C<use> but not C<require>),
620or via a forward reference or C<use subs> declaration. Even in this
621case, you get a clean @_ without any of the old values leaking through
622where they don't belong.
623
624=head2 How do I create a switch or case statement?
625
626This is explained in more depth in the L<perlsyn>. Briefly, there's
627no official case statement, because of the variety of tests possible
628in Perl (numeric comparison, string comparison, glob comparison,
629regexp matching, overloaded comparisons, ...). Larry couldn't decide
630how best to do this, so he left it out, even though it's been on the
631wish list since perl1.
632
c8db1d39 633The general answer is to write a construct like this:
634
635 for ($variable_to_test) {
636 if (/pat1/) { } # do something
637 elsif (/pat2/) { } # do something else
638 elsif (/pat3/) { } # do something else
639 else { } # default
640 }
68dc0745 641
c8db1d39 642Here's a simple example of a switch based on pattern matching, this
643time lined up in a way to make it look more like a switch statement.
644We'll do a multi-way conditional based on the type of reference stored
645in $whatchamacallit:
646
647 SWITCH: for (ref $whatchamacallit) {
68dc0745 648
649 /^$/ && die "not a reference";
650
651 /SCALAR/ && do {
652 print_scalar($$ref);
653 last SWITCH;
654 };
655
656 /ARRAY/ && do {
657 print_array(@$ref);
658 last SWITCH;
659 };
660
661 /HASH/ && do {
662 print_hash(%$ref);
663 last SWITCH;
664 };
665
666 /CODE/ && do {
667 warn "can't print function ref";
668 last SWITCH;
669 };
670
671 # DEFAULT
672
673 warn "User defined type skipped";
674
675 }
676
c8db1d39 677See C<perlsyn/"Basic BLOCKs and Switch Statements"> for many other
678examples in this style.
679
680Sometimes you should change the positions of the constant and the variable.
681For example, let's say you wanted to test which of many answers you were
682given, but in a case-insensitive way that also allows abbreviations.
683You can use the following technique if the strings all start with
684different characters, or if you want to arrange the matches so that
685one takes precedence over another, as C<"SEND"> has precedence over
686C<"STOP"> here:
687
688 chomp($answer = <>);
689 if ("SEND" =~ /^\Q$answer/i) { print "Action is send\n" }
690 elsif ("STOP" =~ /^\Q$answer/i) { print "Action is stop\n" }
691 elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
692 elsif ("LIST" =~ /^\Q$answer/i) { print "Action is list\n" }
693 elsif ("EDIT" =~ /^\Q$answer/i) { print "Action is edit\n" }
694
695A totally different approach is to create a hash of function references.
696
697 my %commands = (
698 "happy" => \&joy,
699 "sad", => \&sullen,
700 "done" => sub { die "See ya!" },
701 "mad" => \&angry,
702 );
703
704 print "How are you? ";
705 chomp($string = <STDIN>);
706 if ($commands{$string}) {
707 $commands{$string}->();
708 } else {
709 print "No such command: $string\n";
710 }
711
68dc0745 712=head2 How can I catch accesses to undefined variables/functions/methods?
713
714The AUTOLOAD method, discussed in L<perlsub/"Autoloading"> and
715L<perltoot/"AUTOLOAD: Proxy Methods">, lets you capture calls to
716undefined functions and methods.
717
718When it comes to undefined variables that would trigger a warning
719under C<-w>, you can use a handler to trap the pseudo-signal
720C<__WARN__> like this:
721
722 $SIG{__WARN__} = sub {
723
c8db1d39 724 for ( $_[0] ) { # voici un switch statement
68dc0745 725
726 /Use of uninitialized value/ && do {
727 # promote warning to a fatal
728 die $_;
729 };
730
731 # other warning cases to catch could go here;
732
733 warn $_;
734 }
735
736 };
737
738=head2 Why can't a method included in this same file be found?
739
740Some possible reasons: your inheritance is getting confused, you've
741misspelled the method name, or the object is of the wrong type. Check
742out L<perltoot> for details on these. You may also use C<print
743ref($object)> to find out the class C<$object> was blessed into.
744
745Another possible reason for problems is because you've used the
746indirect object syntax (eg, C<find Guru "Samy">) on a class name
747before Perl has seen that such a package exists. It's wisest to make
748sure your packages are all defined before you start using them, which
749will be taken care of if you use the C<use> statement instead of
750C<require>. If not, make sure to use arrow notation (eg,
7b8d334a 751C<Guru-E<gt>find("Samy")>) instead. Object notation is explained in
68dc0745 752L<perlobj>.
753
c8db1d39 754Make sure to read about creating modules in L<perlmod> and
755the perils of indirect objects in L<perlobj/"WARNING">.
756
68dc0745 757=head2 How can I find out my current package?
758
759If you're just a random program, you can do this to find
760out what the currently compiled package is:
761
c8db1d39 762 my $packname = __PACKAGE__;
68dc0745 763
764But if you're a method and you want to print an error message
765that includes the kind of object you were called on (which is
766not necessarily the same as the one in which you were compiled):
767
768 sub amethod {
92c2ed05 769 my $self = shift;
68dc0745 770 my $class = ref($self) || $self;
771 warn "called me from a $class object";
772 }
773
46fc3d4c 774=head2 How can I comment out a large block of perl code?
775
776Use embedded POD to discard it:
777
778 # program is here
779
780 =for nobody
781 This paragraph is commented out
782
783 # program continues
784
785 =begin comment text
786
787 all of this stuff
788
789 here will be ignored
790 by everyone
791
792 =end comment text
793
fc36a67e 794 =cut
795
c8db1d39 796This can't go just anywhere. You have to put a pod directive where
797the parser is expecting a new statement, not just in the middle
798of an expression or some other arbitrary yacc grammar production.
799
68dc0745 800=head1 AUTHOR AND COPYRIGHT
801
5a964f20 802Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington.
803All rights reserved.
804
805When included as part of the Standard Version of Perl, or as part of
806its complete documentation whether printed or otherwise, this work
807may be distributed only under the terms of Perl's Artistic License.
808Any distribution of this file or derivatives thereof I<outside>
809of that package require that special arrangements be made with
810copyright holder.
811
812Irrespective of its distribution, all code examples in this file
813are hereby placed into the public domain. You are permitted and
814encouraged to use this code in your own programs for fun
815or for profit as you see fit. A simple comment in the code giving
816credit would be courteous but is not required.