This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Point submitters to perlbug@perl.org, not perl5-porters@perl.org
[perl5.git] / pod / perllexwarn.pod
1 =head1 NAME
2 X<warning, lexical> X<warnings> X<warning>
3
4 perllexwarn - Perl Lexical Warnings
5
6 =head1 DESCRIPTION
7
8 The C<use warnings> pragma enables to control precisely what warnings are
9 to be enabled in which parts of a Perl program. It's a more flexible
10 alternative for both the command line flag B<-w> and the equivalent Perl
11 variable, C<$^W>.
12
13 This pragma works just like the C<strict> pragma.
14 This means that the scope of the warning pragma is limited to the
15 enclosing block. It also means that the pragma setting will not
16 leak across files (via C<use>, C<require> or C<do>). This allows
17 authors to independently define the degree of warning checks that will
18 be applied to their module.
19
20 By default, optional warnings are disabled, so any legacy code that
21 doesn't attempt to control the warnings will work unchanged.
22
23 All warnings are enabled in a block by either of these:
24
25     use warnings;
26     use warnings 'all';
27
28 Similarly all warnings are disabled in a block by either of these:
29
30     no warnings;
31     no warnings 'all';
32
33 For example, consider the code below:
34
35     use warnings;
36     my @a;
37     {
38         no warnings;
39         my $b = @a[0];
40     }
41     my $c = @a[0];
42
43 The code in the enclosing block has warnings enabled, but the inner
44 block has them disabled. In this case that means the assignment to the
45 scalar C<$c> will trip the C<"Scalar value @a[0] better written as $a[0]">
46 warning, but the assignment to the scalar C<$b> will not.
47
48 =head2 Default Warnings and Optional Warnings
49
50 Before the introduction of lexical warnings, Perl had two classes of
51 warnings: mandatory and optional. 
52
53 As its name suggests, if your code tripped a mandatory warning, you
54 would get a warning whether you wanted it or not.
55 For example, the code below would always produce an C<"isn't numeric">
56 warning about the "2:".
57
58     my $a = "2:" + 3;
59
60 With the introduction of lexical warnings, mandatory warnings now become
61 I<default> warnings. The difference is that although the previously
62 mandatory warnings are still enabled by default, they can then be
63 subsequently enabled or disabled with the lexical warning pragma. For
64 example, in the code below, an C<"isn't numeric"> warning will only
65 be reported for the C<$a> variable.
66
67     my $a = "2:" + 3;
68     no warnings;
69     my $b = "2:" + 3;
70
71 Note that neither the B<-w> flag or the C<$^W> can be used to
72 disable/enable default warnings. They are still mandatory in this case.
73
74 =head2 What's wrong with B<-w> and C<$^W>
75
76 Although very useful, the big problem with using B<-w> on the command
77 line to enable warnings is that it is all or nothing. Take the typical
78 scenario when you are writing a Perl program. Parts of the code you
79 will write yourself, but it's very likely that you will make use of
80 pre-written Perl modules. If you use the B<-w> flag in this case, you
81 end up enabling warnings in pieces of code that you haven't written.
82
83 Similarly, using C<$^W> to either disable or enable blocks of code is
84 fundamentally flawed. For a start, say you want to disable warnings in
85 a block of code. You might expect this to be enough to do the trick:
86
87      {
88          local ($^W) = 0;
89          my $a =+ 2;
90          my $b; chop $b;
91      }
92
93 When this code is run with the B<-w> flag, a warning will be produced
94 for the C<$a> line:  C<"Reversed += operator">.
95
96 The problem is that Perl has both compile-time and run-time warnings. To
97 disable compile-time warnings you need to rewrite the code like this:
98
99      {
100          BEGIN { $^W = 0 }
101          my $a =+ 2;
102          my $b; chop $b;
103      }
104
105 The other big problem with C<$^W> is the way you can inadvertently
106 change the warning setting in unexpected places in your code. For example,
107 when the code below is run (without the B<-w> flag), the second call
108 to C<doit> will trip a C<"Use of uninitialized value"> warning, whereas
109 the first will not.
110
111     sub doit
112     {
113         my $b; chop $b;
114     }
115
116     doit();
117
118     {
119         local ($^W) = 1;
120         doit()
121     }
122
123 This is a side-effect of C<$^W> being dynamically scoped.
124
125 Lexical warnings get around these limitations by allowing finer control
126 over where warnings can or can't be tripped.
127
128 =head2 Controlling Warnings from the Command Line
129
130 There are three Command Line flags that can be used to control when
131 warnings are (or aren't) produced:
132
133 =over 5
134
135 =item B<-w>
136 X<-w>
137
138 This is  the existing flag. If the lexical warnings pragma is B<not>
139 used in any of you code, or any of the modules that you use, this flag
140 will enable warnings everywhere. See L<Backward Compatibility> for
141 details of how this flag interacts with lexical warnings.
142
143 =item B<-W>
144 X<-W>
145
146 If the B<-W> flag is used on the command line, it will enable all warnings
147 throughout the program regardless of whether warnings were disabled
148 locally using C<no warnings> or C<$^W =0>. This includes all files that get
149 included via C<use>, C<require> or C<do>.
150 Think of it as the Perl equivalent of the "lint" command.
151
152 =item B<-X>
153 X<-X>
154
155 Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.
156
157 =back
158
159 =head2 Backward Compatibility
160
161 If you are used with working with a version of Perl prior to the
162 introduction of lexically scoped warnings, or have code that uses both
163 lexical warnings and C<$^W>, this section will describe how they interact.
164
165 How Lexical Warnings interact with B<-w>/C<$^W>:
166
167 =over 5
168
169 =item 1.
170
171 If none of the three command line flags (B<-w>, B<-W> or B<-X>) that
172 control warnings is used and neither C<$^W> or the C<warnings> pragma
173 are used, then default warnings will be enabled and optional warnings
174 disabled.
175 This means that legacy code that doesn't attempt to control the warnings
176 will work unchanged.
177
178 =item 2.
179
180 The B<-w> flag just sets the global C<$^W> variable as in 5.005. This
181 means that any legacy code that currently relies on manipulating C<$^W>
182 to control warning behavior will still work as is. 
183
184 =item 3.
185
186 Apart from now being a boolean, the C<$^W> variable operates in exactly
187 the same horrible uncontrolled global way, except that it cannot
188 disable/enable default warnings.
189
190 =item 4.
191
192 If a piece of code is under the control of the C<warnings> pragma,
193 both the C<$^W> variable and the B<-w> flag will be ignored for the
194 scope of the lexical warning.
195
196 =item 5.
197
198 The only way to override a lexical warnings setting is with the B<-W>
199 or B<-X> command line flags.
200
201 =back
202
203 The combined effect of 3 & 4 is that it will allow code which uses
204 the C<warnings> pragma to control the warning behavior of $^W-type
205 code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
206
207 =head2 Category Hierarchy
208 X<warning, categories>
209
210 A hierarchy of "categories" have been defined to allow groups of warnings
211 to be enabled/disabled in isolation.
212
213 The current hierarchy is:
214
215   all -+
216        |
217        +- closure
218        |
219        +- deprecated
220        |
221        +- exiting
222        |
223        +- glob
224        |
225        +- io -----------+
226        |                |
227        |                +- closed
228        |                |
229        |                +- exec
230        |                |
231        |                +- layer
232        |                |
233        |                +- newline
234        |                |
235        |                +- pipe
236        |                |
237        |                +- unopened
238        |
239        +- imprecision
240        |
241        +- misc
242        |
243        +- numeric
244        |
245        +- once
246        |
247        +- overflow
248        |
249        +- pack
250        |
251        +- portable
252        |
253        +- recursion
254        |
255        +- redefine
256        |
257        +- regexp
258        |
259        +- severe -------+
260        |                |
261        |                +- debugging
262        |                |
263        |                +- inplace
264        |                |
265        |                +- internal
266        |                |
267        |                +- malloc
268        |
269        +- signal
270        |
271        +- substr
272        |
273        +- syntax -------+
274        |                |
275        |                +- ambiguous
276        |                |
277        |                +- bareword
278        |                |
279        |                +- digit
280        |                |
281        |                +- illegalproto
282        |                |
283        |                +- parenthesis
284        |                |
285        |                +- precedence
286        |                |
287        |                +- printf
288        |                |
289        |                +- prototype
290        |                |
291        |                +- qw
292        |                |
293        |                +- reserved
294        |                |
295        |                +- semicolon
296        |
297        +- taint
298        |
299        +- threads
300        |
301        +- uninitialized
302        |
303        +- unpack
304        |
305        +- untie
306        |
307        +- utf8
308        |
309        +- void
310
311 Just like the "strict" pragma any of these categories can be combined
312
313     use warnings qw(void redefine);
314     no warnings qw(io syntax untie);
315
316 Also like the "strict" pragma, if there is more than one instance of the
317 C<warnings> pragma in a given scope the cumulative effect is additive. 
318
319     use warnings qw(void); # only "void" warnings enabled
320     ...
321     use warnings qw(io);   # only "void" & "io" warnings enabled
322     ...
323     no warnings qw(void);  # only "io" warnings enabled
324
325 To determine which category a specific warning has been assigned to see
326 L<perldiag>.
327
328 Note: In Perl 5.6.1, the lexical warnings category "deprecated" was a
329 sub-category of the "syntax" category. It is now a top-level category
330 in its own right.
331
332
333 =head2 Fatal Warnings
334 X<warning, fatal>
335
336 The presence of the word "FATAL" in the category list will escalate any
337 warnings detected from the categories specified in the lexical scope
338 into fatal errors. In the code below, the use of C<time>, C<length>
339 and C<join> can all produce a C<"Useless use of xxx in void context">
340 warning.
341
342     use warnings;
343
344     time;
345
346     {
347         use warnings FATAL => qw(void);
348         length "abc";
349     }
350
351     join "", 1,2,3;
352
353     print "done\n";
354
355 When run it produces this output
356
357     Useless use of time in void context at fatal line 3.
358     Useless use of length in void context at fatal line 7.  
359
360 The scope where C<length> is used has escalated the C<void> warnings
361 category into a fatal error, so the program terminates immediately it
362 encounters the warning.
363
364 To explicitly turn off a "FATAL" warning you just disable the warning
365 it is associated with.  So, for example, to disable the "void" warning
366 in the example above, either of these will do the trick:
367
368     no warnings qw(void);
369     no warnings FATAL => qw(void);
370
371 If you want to downgrade a warning that has been escalated into a fatal
372 error back to a normal warning, you can use the "NONFATAL" keyword. For
373 example, the code below will promote all warnings into fatal errors,
374 except for those in the "syntax" category.
375
376     use warnings FATAL => 'all', NONFATAL => 'syntax';
377
378 =head2 Reporting Warnings from a Module
379 X<warning, reporting> X<warning, registering>
380
381 The C<warnings> pragma provides a number of functions that are useful for
382 module authors. These are used when you want to report a module-specific
383 warning to a calling module has enabled warnings via the C<warnings>
384 pragma.
385
386 Consider the module C<MyMod::Abc> below.
387
388     package MyMod::Abc;
389
390     use warnings::register;
391
392     sub open {
393         my $path = shift;
394         if ($path !~ m#^/#) {
395             warnings::warn("changing relative path to /var/abc")
396                 if warnings::enabled();
397             $path = "/var/abc/$path";
398         }
399     }
400
401     1;
402
403 The call to C<warnings::register> will create a new warnings category
404 called "MyMod::Abc", i.e. the new category name matches the current
405 package name. The C<open> function in the module will display a warning
406 message if it gets given a relative path as a parameter. This warnings
407 will only be displayed if the code that uses C<MyMod::Abc> has actually
408 enabled them with the C<warnings> pragma like below.
409
410     use MyMod::Abc;
411     use warnings 'MyMod::Abc';
412     ...
413     abc::open("../fred.txt");
414
415 It is also possible to test whether the pre-defined warnings categories are
416 set in the calling module with the C<warnings::enabled> function. Consider
417 this snippet of code:
418
419     package MyMod::Abc;
420
421     sub open {
422         warnings::warnif("deprecated", 
423                          "open is deprecated, use new instead");
424         new(@_);
425     }
426
427     sub new
428     ...
429     1;
430
431 The function C<open> has been deprecated, so code has been included to
432 display a warning message whenever the calling module has (at least) the
433 "deprecated" warnings category enabled. Something like this, say.
434
435     use warnings 'deprecated';
436     use MyMod::Abc;
437     ...
438     MyMod::Abc::open($filename);
439
440 Either the C<warnings::warn> or C<warnings::warnif> function should be
441 used to actually display the warnings message. This is because they can
442 make use of the feature that allows warnings to be escalated into fatal
443 errors. So in this case
444
445     use MyMod::Abc;
446     use warnings FATAL => 'MyMod::Abc';
447     ...
448     MyMod::Abc::open('../fred.txt');
449
450 the C<warnings::warnif> function will detect this and die after
451 displaying the warning message.
452
453 The three warnings functions, C<warnings::warn>, C<warnings::warnif>
454 and C<warnings::enabled> can optionally take an object reference in place
455 of a category name. In this case the functions will use the class name
456 of the object as the warnings category.
457
458 Consider this example:
459
460     package Original;
461
462     no warnings;
463     use warnings::register;
464
465     sub new
466     {
467         my $class = shift;
468         bless [], $class;
469     }
470
471     sub check
472     {
473         my $self = shift;
474         my $value = shift;
475
476         if ($value % 2 && warnings::enabled($self))
477           { warnings::warn($self, "Odd numbers are unsafe") }
478     }
479
480     sub doit
481     {
482         my $self = shift;
483         my $value = shift;
484         $self->check($value);
485         # ...
486     }
487
488     1;
489
490     package Derived;
491
492     use warnings::register;
493     use Original;
494     our @ISA = qw( Original );
495     sub new
496     {
497         my $class = shift;
498         bless [], $class;
499     }
500
501
502     1;
503
504 The code below makes use of both modules, but it only enables warnings from 
505 C<Derived>.
506
507     use Original;
508     use Derived;
509     use warnings 'Derived';
510     my $a = Original->new();
511     $a->doit(1);
512     my $b = Derived->new();
513     $a->doit(1);
514
515 When this code is run only the C<Derived> object, C<$b>, will generate
516 a warning. 
517
518     Odd numbers are unsafe at main.pl line 7
519
520 Notice also that the warning is reported at the line where the object is first
521 used.
522
523 =head1 SEE ALSO
524
525 L<warnings>, L<perldiag>.
526
527 =head1 AUTHOR
528
529 Paul Marquess