1warnings(3pm) Perl Programmers Reference Guide warnings(3pm)
2
3
4
6 warnings - Perl pragma to control optional warnings
7
9 use warnings;
10 no warnings;
11
12 # Standard warnings are enabled by use v5.35 or above
13 use v5.35;
14
15 use warnings "all";
16 no warnings "uninitialized";
17
18 # or equivalent to those last two ...
19 use warnings qw(all -uninitialized);
20
21 use warnings::register;
22 if (warnings::enabled()) {
23 warnings::warn("some warning");
24 }
25
26 if (warnings::enabled("void")) {
27 warnings::warn("void", "some warning");
28 }
29
30 if (warnings::enabled($object)) {
31 warnings::warn($object, "some warning");
32 }
33
34 warnings::warnif("some warning");
35 warnings::warnif("void", "some warning");
36 warnings::warnif($object, "some warning");
37
39 The "warnings" pragma gives control over which warnings are enabled in
40 which parts of a Perl program. It's a more flexible alternative for
41 both the command line flag -w and the equivalent Perl variable, $^W.
42
43 This pragma works just like the "strict" pragma. This means that the
44 scope of the warning pragma is limited to the enclosing block. It also
45 means that the pragma setting will not leak across files (via "use",
46 "require" or "do"). This allows authors to independently define the
47 degree of warning checks that will be applied to their module.
48
49 By default, optional warnings are disabled, so any legacy code that
50 doesn't attempt to control the warnings will work unchanged.
51
52 All warnings are enabled in a block by either of these:
53
54 use warnings;
55 use warnings 'all';
56
57 Similarly all warnings are disabled in a block by either of these:
58
59 no warnings;
60 no warnings 'all';
61
62 For example, consider the code below:
63
64 use warnings;
65 my @x;
66 {
67 no warnings;
68 my $y = @x[0];
69 }
70 my $z = @x[0];
71
72 The code in the enclosing block has warnings enabled, but the inner
73 block has them disabled. In this case that means the assignment to the
74 scalar $z will trip the "Scalar value @x[0] better written as $x[0]"
75 warning, but the assignment to the scalar $y will not.
76
77 All warnings are enabled automatically within the scope of a "use
78 v5.35" (or higher) declaration.
79
80 Default Warnings and Optional Warnings
81 Before the introduction of lexical warnings, Perl had two classes of
82 warnings: mandatory and optional.
83
84 As its name suggests, if your code tripped a mandatory warning, you
85 would get a warning whether you wanted it or not. For example, the
86 code below would always produce an "isn't numeric" warning about the
87 "2:".
88
89 my $x = "2:" + 3;
90
91 With the introduction of lexical warnings, mandatory warnings now
92 become default warnings. The difference is that although the
93 previously mandatory warnings are still enabled by default, they can
94 then be subsequently enabled or disabled with the lexical warning
95 pragma. For example, in the code below, an "isn't numeric" warning
96 will only be reported for the $x variable.
97
98 my $x = "2:" + 3;
99 no warnings;
100 my $y = "2:" + 3;
101
102 Note that neither the -w flag or the $^W can be used to disable/enable
103 default warnings. They are still mandatory in this case.
104
105 "Negative warnings"
106 As a convenience, you can (as of Perl 5.34) pass arguments to the
107 "import()" method both positively and negatively. Negative warnings are
108 those with a "-" sign prepended to their names; positive warnings are
109 anything else. This lets you turn on some warnings and turn off others
110 in one command. So, assuming that you've already turned on a bunch of
111 warnings but want to tweak them a bit in some block, you can do this:
112
113 {
114 use warnings qw(uninitialized -redefine);
115 ...
116 }
117
118 which is equivalent to:
119
120 {
121 use warnings qw(uninitialized);
122 no warnings qw(redefine);
123 ...
124 }
125
126 The argument list is processed in the order you specify. So, for
127 example, if you don't want to be warned about use of experimental
128 features, except for "somefeature" that you really dislike, you can say
129 this:
130
131 use warnings qw(all -experimental experimental::somefeature);
132
133 which is equivalent to:
134
135 use warnings 'all';
136 no warnings 'experimental';
137 use warnings 'experimental::somefeature';
138
139 What's wrong with -w and $^W
140 Although very useful, the big problem with using -w on the command line
141 to enable warnings is that it is all or nothing. Take the typical
142 scenario when you are writing a Perl program. Parts of the code you
143 will write yourself, but it's very likely that you will make use of
144 pre-written Perl modules. If you use the -w flag in this case, you end
145 up enabling warnings in pieces of code that you haven't written.
146
147 Similarly, using $^W to either disable or enable blocks of code is
148 fundamentally flawed. For a start, say you want to disable warnings in
149 a block of code. You might expect this to be enough to do the trick:
150
151 {
152 local ($^W) = 0;
153 my $x =+ 2;
154 my $y; chop $y;
155 }
156
157 When this code is run with the -w flag, a warning will be produced for
158 the $x line: "Reversed += operator".
159
160 The problem is that Perl has both compile-time and run-time warnings.
161 To disable compile-time warnings you need to rewrite the code like
162 this:
163
164 {
165 BEGIN { $^W = 0 }
166 my $x =+ 2;
167 my $y; chop $y;
168 }
169
170 And note that unlike the first example, this will permanently set $^W
171 since it cannot both run during compile-time and be localized to a run-
172 time block.
173
174 The other big problem with $^W is the way you can inadvertently change
175 the warning setting in unexpected places in your code. For example,
176 when the code below is run (without the -w flag), the second call to
177 "doit" will trip a "Use of uninitialized value" warning, whereas the
178 first will not.
179
180 sub doit
181 {
182 my $y; chop $y;
183 }
184
185 doit();
186
187 {
188 local ($^W) = 1;
189 doit()
190 }
191
192 This is a side-effect of $^W being dynamically scoped.
193
194 Lexical warnings get around these limitations by allowing finer control
195 over where warnings can or can't be tripped.
196
197 Controlling Warnings from the Command Line
198 There are three Command Line flags that can be used to control when
199 warnings are (or aren't) produced:
200
201 -w This is the existing flag. If the lexical warnings pragma is not
202 used in any of your code, or any of the modules that you use, this
203 flag will enable warnings everywhere. See "Backward
204 Compatibility" for details of how this flag interacts with lexical
205 warnings.
206
207 -W If the -W flag is used on the command line, it will enable all
208 warnings throughout the program regardless of whether warnings
209 were disabled locally using "no warnings" or "$^W =0". This
210 includes all files that get included via "use", "require" or "do".
211 Think of it as the Perl equivalent of the "lint" command.
212
213 -X Does the exact opposite to the -W flag, i.e. it disables all
214 warnings.
215
216 Backward Compatibility
217 If you are used to working with a version of Perl prior to the
218 introduction of lexically scoped warnings, or have code that uses both
219 lexical warnings and $^W, this section will describe how they interact.
220
221 How Lexical Warnings interact with -w/$^W:
222
223 1. If none of the three command line flags (-w, -W or -X) that
224 control warnings is used and neither $^W nor the "warnings" pragma
225 are used, then default warnings will be enabled and optional
226 warnings disabled. This means that legacy code that doesn't
227 attempt to control the warnings will work unchanged.
228
229 2. The -w flag just sets the global $^W variable as in 5.005. This
230 means that any legacy code that currently relies on manipulating
231 $^W to control warning behavior will still work as is.
232
233 3. Apart from now being a boolean, the $^W variable operates in
234 exactly the same horrible uncontrolled global way, except that it
235 cannot disable/enable default warnings.
236
237 4. If a piece of code is under the control of the "warnings" pragma,
238 both the $^W variable and the -w flag will be ignored for the
239 scope of the lexical warning.
240
241 5. The only way to override a lexical warnings setting is with the -W
242 or -X command line flags.
243
244 The combined effect of 3 & 4 is that it will allow code which uses the
245 "warnings" pragma to control the warning behavior of $^W-type code
246 (using a "local $^W=0") if it really wants to, but not vice-versa.
247
248 Category Hierarchy
249 A hierarchy of "categories" have been defined to allow groups of
250 warnings to be enabled/disabled in isolation.
251
252 The current hierarchy is:
253
254 all -+
255 |
256 +- closure
257 |
258 +- deprecated
259 |
260 +- exiting
261 |
262 +- experimental --+
263 | |
264 | +- experimental::alpha_assertions
265 | |
266 | +- experimental::args_array_with_signatures
267 | |
268 | +- experimental::bitwise
269 | |
270 | +- experimental::builtin
271 | |
272 | +- experimental::const_attr
273 | |
274 | +- experimental::declared_refs
275 | |
276 | +- experimental::defer
277 | |
278 | +- experimental::extra_paired_delimiters
279 | |
280 | +- experimental::for_list
281 | |
282 | +- experimental::isa
283 | |
284 | +- experimental::lexical_subs
285 | |
286 | +- experimental::postderef
287 | |
288 | +- experimental::private_use
289 | |
290 | +- experimental::re_strict
291 | |
292 | +- experimental::refaliasing
293 | |
294 | +- experimental::regex_sets
295 | |
296 | +- experimental::script_run
297 | |
298 | +- experimental::signatures
299 | |
300 | +- experimental::smartmatch
301 | |
302 | +- experimental::try
303 | |
304 | +- experimental::uniprop_wildcards
305 | |
306 | +- experimental::vlb
307 |
308 +- glob
309 |
310 +- imprecision
311 |
312 +- io ------------+
313 | |
314 | +- closed
315 | |
316 | +- exec
317 | |
318 | +- layer
319 | |
320 | +- newline
321 | |
322 | +- pipe
323 | |
324 | +- syscalls
325 | |
326 | +- unopened
327 |
328 +- locale
329 |
330 +- misc
331 |
332 +- missing
333 |
334 +- numeric
335 |
336 +- once
337 |
338 +- overflow
339 |
340 +- pack
341 |
342 +- portable
343 |
344 +- recursion
345 |
346 +- redefine
347 |
348 +- redundant
349 |
350 +- regexp
351 |
352 +- scalar
353 |
354 +- severe --------+
355 | |
356 | +- debugging
357 | |
358 | +- inplace
359 | |
360 | +- internal
361 | |
362 | +- malloc
363 |
364 +- shadow
365 |
366 +- signal
367 |
368 +- substr
369 |
370 +- syntax --------+
371 | |
372 | +- ambiguous
373 | |
374 | +- bareword
375 | |
376 | +- digit
377 | |
378 | +- illegalproto
379 | |
380 | +- parenthesis
381 | |
382 | +- precedence
383 | |
384 | +- printf
385 | |
386 | +- prototype
387 | |
388 | +- qw
389 | |
390 | +- reserved
391 | |
392 | +- semicolon
393 |
394 +- taint
395 |
396 +- threads
397 |
398 +- uninitialized
399 |
400 +- unpack
401 |
402 +- untie
403 |
404 +- utf8 ----------+
405 | |
406 | +- non_unicode
407 | |
408 | +- nonchar
409 | |
410 | +- surrogate
411 |
412 +- void
413
414 Just like the "strict" pragma any of these categories can be combined
415
416 use warnings qw(void redefine);
417 no warnings qw(io syntax untie);
418
419 Also like the "strict" pragma, if there is more than one instance of
420 the "warnings" pragma in a given scope the cumulative effect is
421 additive.
422
423 use warnings qw(void); # only "void" warnings enabled
424 ...
425 use warnings qw(io); # only "void" & "io" warnings enabled
426 ...
427 no warnings qw(void); # only "io" warnings enabled
428
429 To determine which category a specific warning has been assigned to see
430 perldiag.
431
432 Note: Before Perl 5.8.0, the lexical warnings category "deprecated" was
433 a sub-category of the "syntax" category. It is now a top-level
434 category in its own right.
435
436 Note: Before 5.21.0, the "missing" lexical warnings category was
437 internally defined to be the same as the "uninitialized" category. It
438 is now a top-level category in its own right.
439
440 Fatal Warnings
441 The presence of the word "FATAL" in the category list will escalate
442 warnings in those categories into fatal errors in that lexical scope.
443
444 NOTE: FATAL warnings should be used with care, particularly "FATAL =>
445 'all'".
446
447 Libraries using warnings::warn for custom warning categories generally
448 don't expect warnings::warn to be fatal and can wind up in an
449 unexpected state as a result. For XS modules issuing categorized
450 warnings, such unanticipated exceptions could also expose memory leak
451 bugs.
452
453 Moreover, the Perl interpreter itself has had serious bugs involving
454 fatalized warnings. For a summary of resolved and unresolved problems
455 as of January 2015, please see this perl5-porters post
456 <http://www.nntp.perl.org/group/perl.perl5.porters/2015/01/msg225235.html>.
457
458 While some developers find fatalizing some warnings to be a useful
459 defensive programming technique, using "FATAL => 'all'" to fatalize all
460 possible warning categories -- including custom ones -- is particularly
461 risky. Therefore, the use of "FATAL => 'all'" is discouraged.
462
463 The strictures module on CPAN offers one example of a warnings subset
464 that the module's authors believe is relatively safe to fatalize.
465
466 NOTE: Users of FATAL warnings, especially those using "FATAL => 'all'",
467 should be fully aware that they are risking future portability of their
468 programs by doing so. Perl makes absolutely no commitments to not
469 introduce new warnings or warnings categories in the future; indeed, we
470 explicitly reserve the right to do so. Code that may not warn now may
471 warn in a future release of Perl if the Perl5 development team deems it
472 in the best interests of the community to do so. Should code using
473 FATAL warnings break due to the introduction of a new warning we will
474 NOT consider it an incompatible change. Users of FATAL warnings should
475 take special caution during upgrades to check to see if their code
476 triggers any new warnings and should pay particular attention to the
477 fine print of the documentation of the features they use to ensure they
478 do not exploit features that are documented as risky, deprecated, or
479 unspecified, or where the documentation says "so don't do that", or
480 anything with the same sense and spirit. Use of such features in
481 combination with FATAL warnings is ENTIRELY AT THE USER'S RISK.
482
483 The following documentation describes how to use FATAL warnings but the
484 perl5 porters strongly recommend that you understand the risks before
485 doing so, especially for library code intended for use by others, as
486 there is no way for downstream users to change the choice of fatal
487 categories.
488
489 In the code below, the use of "time", "length" and "join" can all
490 produce a "Useless use of xxx in void context" warning.
491
492 use warnings;
493
494 time;
495
496 {
497 use warnings FATAL => qw(void);
498 length "abc";
499 }
500
501 join "", 1,2,3;
502
503 print "done\n";
504
505 When run it produces this output
506
507 Useless use of time in void context at fatal line 3.
508 Useless use of length in void context at fatal line 7.
509
510 The scope where "length" is used has escalated the "void" warnings
511 category into a fatal error, so the program terminates immediately when
512 it encounters the warning.
513
514 To explicitly turn off a "FATAL" warning you just disable the warning
515 it is associated with. So, for example, to disable the "void" warning
516 in the example above, either of these will do the trick:
517
518 no warnings qw(void);
519 no warnings FATAL => qw(void);
520
521 If you want to downgrade a warning that has been escalated into a fatal
522 error back to a normal warning, you can use the "NONFATAL" keyword.
523 For example, the code below will promote all warnings into fatal
524 errors, except for those in the "syntax" category.
525
526 use warnings FATAL => 'all', NONFATAL => 'syntax';
527
528 As of Perl 5.20, instead of "use warnings FATAL => 'all';" you can use:
529
530 use v5.20; # Perl 5.20 or greater is required for the following
531 use warnings 'FATAL'; # short form of "use warnings FATAL => 'all';"
532
533 However, you should still heed the guidance earlier in this section
534 against using "use warnings FATAL => 'all';".
535
536 If you want your program to be compatible with versions of Perl before
537 5.20, you must use "use warnings FATAL => 'all';" instead. (In
538 previous versions of Perl, the behavior of the statements "use warnings
539 'FATAL';", "use warnings 'NONFATAL';" and "no warnings 'FATAL';" was
540 unspecified; they did not behave as if they included the "=> 'all'"
541 portion. As of 5.20, they do.)
542
543 Reporting Warnings from a Module
544 The "warnings" pragma provides a number of functions that are useful
545 for module authors. These are used when you want to report a module-
546 specific warning to a calling module has enabled warnings via the
547 "warnings" pragma.
548
549 Consider the module "MyMod::Abc" below.
550
551 package MyMod::Abc;
552
553 use warnings::register;
554
555 sub open {
556 my $path = shift;
557 if ($path !~ m#^/#) {
558 warnings::warn("changing relative path to /var/abc")
559 if warnings::enabled();
560 $path = "/var/abc/$path";
561 }
562 }
563
564 1;
565
566 The call to "warnings::register" will create a new warnings category
567 called "MyMod::Abc", i.e. the new category name matches the current
568 package name. The "open" function in the module will display a warning
569 message if it gets given a relative path as a parameter. This warnings
570 will only be displayed if the code that uses "MyMod::Abc" has actually
571 enabled them with the "warnings" pragma like below.
572
573 use MyMod::Abc;
574 use warnings 'MyMod::Abc';
575 ...
576 abc::open("../fred.txt");
577
578 It is also possible to test whether the pre-defined warnings categories
579 are set in the calling module with the "warnings::enabled" function.
580 Consider this snippet of code:
581
582 package MyMod::Abc;
583
584 sub open {
585 if (warnings::enabled("deprecated")) {
586 warnings::warn("deprecated",
587 "open is deprecated, use new instead");
588 }
589 new(@_);
590 }
591
592 sub new
593 ...
594 1;
595
596 The function "open" has been deprecated, so code has been included to
597 display a warning message whenever the calling module has (at least)
598 the "deprecated" warnings category enabled. Something like this, say.
599
600 use warnings 'deprecated';
601 use MyMod::Abc;
602 ...
603 MyMod::Abc::open($filename);
604
605 Either the "warnings::warn" or "warnings::warnif" function should be
606 used to actually display the warnings message. This is because they
607 can make use of the feature that allows warnings to be escalated into
608 fatal errors. So in this case
609
610 use MyMod::Abc;
611 use warnings FATAL => 'MyMod::Abc';
612 ...
613 MyMod::Abc::open('../fred.txt');
614
615 the "warnings::warnif" function will detect this and die after
616 displaying the warning message.
617
618 The three warnings functions, "warnings::warn", "warnings::warnif" and
619 "warnings::enabled" can optionally take an object reference in place of
620 a category name. In this case the functions will use the class name of
621 the object as the warnings category.
622
623 Consider this example:
624
625 package Original;
626
627 no warnings;
628 use warnings::register;
629
630 sub new
631 {
632 my $class = shift;
633 bless [], $class;
634 }
635
636 sub check
637 {
638 my $self = shift;
639 my $value = shift;
640
641 if ($value % 2 && warnings::enabled($self))
642 { warnings::warn($self, "Odd numbers are unsafe") }
643 }
644
645 sub doit
646 {
647 my $self = shift;
648 my $value = shift;
649 $self->check($value);
650 # ...
651 }
652
653 1;
654
655 package Derived;
656
657 use warnings::register;
658 use Original;
659 our @ISA = qw( Original );
660 sub new
661 {
662 my $class = shift;
663 bless [], $class;
664 }
665
666
667 1;
668
669 The code below makes use of both modules, but it only enables warnings
670 from "Derived".
671
672 use Original;
673 use Derived;
674 use warnings 'Derived';
675 my $x = Original->new();
676 $x->doit(1);
677 my $y = Derived->new();
678 $x->doit(1);
679
680 When this code is run only the "Derived" object, $y, will generate a
681 warning.
682
683 Odd numbers are unsafe at main.pl line 7
684
685 Notice also that the warning is reported at the line where the object
686 is first used.
687
688 When registering new categories of warning, you can supply more names
689 to warnings::register like this:
690
691 package MyModule;
692 use warnings::register qw(format precision);
693
694 ...
695
696 warnings::warnif('MyModule::format', '...');
697
699 Note: The functions with names ending in "_at_level" were added in Perl
700 5.28.
701
702 use warnings::register
703 Creates a new warnings category with the same name as the package
704 where the call to the pragma is used.
705
706 warnings::enabled()
707 Use the warnings category with the same name as the current
708 package.
709
710 Return TRUE if that warnings category is enabled in the calling
711 module. Otherwise returns FALSE.
712
713 warnings::enabled($category)
714 Return TRUE if the warnings category, $category, is enabled in the
715 calling module. Otherwise returns FALSE.
716
717 warnings::enabled($object)
718 Use the name of the class for the object reference, $object, as the
719 warnings category.
720
721 Return TRUE if that warnings category is enabled in the first scope
722 where the object is used. Otherwise returns FALSE.
723
724 warnings::enabled_at_level($category, $level)
725 Like "warnings::enabled", but $level specifies the exact call
726 frame, 0 being the immediate caller.
727
728 warnings::fatal_enabled()
729 Return TRUE if the warnings category with the same name as the
730 current package has been set to FATAL in the calling module.
731 Otherwise returns FALSE.
732
733 warnings::fatal_enabled($category)
734 Return TRUE if the warnings category $category has been set to
735 FATAL in the calling module. Otherwise returns FALSE.
736
737 warnings::fatal_enabled($object)
738 Use the name of the class for the object reference, $object, as the
739 warnings category.
740
741 Return TRUE if that warnings category has been set to FATAL in the
742 first scope where the object is used. Otherwise returns FALSE.
743
744 warnings::fatal_enabled_at_level($category, $level)
745 Like "warnings::fatal_enabled", but $level specifies the exact call
746 frame, 0 being the immediate caller.
747
748 warnings::warn($message)
749 Print $message to STDERR.
750
751 Use the warnings category with the same name as the current
752 package.
753
754 If that warnings category has been set to "FATAL" in the calling
755 module then die. Otherwise return.
756
757 warnings::warn($category, $message)
758 Print $message to STDERR.
759
760 If the warnings category, $category, has been set to "FATAL" in the
761 calling module then die. Otherwise return.
762
763 warnings::warn($object, $message)
764 Print $message to STDERR.
765
766 Use the name of the class for the object reference, $object, as the
767 warnings category.
768
769 If that warnings category has been set to "FATAL" in the scope
770 where $object is first used then die. Otherwise return.
771
772 warnings::warn_at_level($category, $level, $message)
773 Like "warnings::warn", but $level specifies the exact call frame, 0
774 being the immediate caller.
775
776 warnings::warnif($message)
777 Equivalent to:
778
779 if (warnings::enabled())
780 { warnings::warn($message) }
781
782 warnings::warnif($category, $message)
783 Equivalent to:
784
785 if (warnings::enabled($category))
786 { warnings::warn($category, $message) }
787
788 warnings::warnif($object, $message)
789 Equivalent to:
790
791 if (warnings::enabled($object))
792 { warnings::warn($object, $message) }
793
794 warnings::warnif_at_level($category, $level, $message)
795 Like "warnings::warnif", but $level specifies the exact call frame,
796 0 being the immediate caller.
797
798 warnings::register_categories(@names)
799 This registers warning categories for the given names and is
800 primarily for use by the warnings::register pragma.
801
802 See also "Pragmatic Modules" in perlmodlib and perldiag.
803
804
805
806perl v5.36.3 2023-11-30 warnings(3pm)