3 # Regenerate (overwriting only if changed):
8 # from information hardcoded into this script (the $tree hash), plus the
9 # template for warnings.pm in the DATA section.
11 # When changing the number of warnings, t/op/caller.t should change to
12 # correspond with the value of $BYTES in lib/warnings.pm
14 # With an argument of 'tree', just dump the contents of $tree and exits.
15 # Also accepts the standard regen_lib -q and -v args.
17 # This script is normally invoked from regen.pl.
22 require 'regen/regen_lib.pl';
27 sub DEFAULT_ON () { 1 }
28 sub DEFAULT_OFF () { 2 }
34 'pipe' => [ 5.008, DEFAULT_OFF],
35 'unopened' => [ 5.008, DEFAULT_OFF],
36 'closed' => [ 5.008, DEFAULT_OFF],
37 'newline' => [ 5.008, DEFAULT_OFF],
38 'exec' => [ 5.008, DEFAULT_OFF],
39 'layer' => [ 5.008, DEFAULT_OFF],
40 'syscalls' => [ 5.019, DEFAULT_OFF],
42 'syntax' => [ 5.008, {
43 'ambiguous' => [ 5.008, DEFAULT_OFF],
44 'semicolon' => [ 5.008, DEFAULT_OFF],
45 'precedence' => [ 5.008, DEFAULT_OFF],
46 'bareword' => [ 5.008, DEFAULT_OFF],
47 'reserved' => [ 5.008, DEFAULT_OFF],
48 'digit' => [ 5.008, DEFAULT_OFF],
49 'parenthesis' => [ 5.008, DEFAULT_OFF],
50 'printf' => [ 5.008, DEFAULT_OFF],
51 'prototype' => [ 5.008, DEFAULT_OFF],
52 'qw' => [ 5.008, DEFAULT_OFF],
53 'illegalproto' => [ 5.011, DEFAULT_OFF],
55 'severe' => [ 5.008, {
56 'inplace' => [ 5.008, DEFAULT_ON],
57 'internal' => [ 5.008, DEFAULT_OFF],
58 'debugging' => [ 5.008, DEFAULT_ON],
59 'malloc' => [ 5.008, DEFAULT_ON],
61 'deprecated' => [ 5.008, DEFAULT_ON],
62 'void' => [ 5.008, DEFAULT_OFF],
63 'recursion' => [ 5.008, DEFAULT_OFF],
64 'redefine' => [ 5.008, DEFAULT_OFF],
65 'numeric' => [ 5.008, DEFAULT_OFF],
66 'uninitialized' => [ 5.008, DEFAULT_OFF],
67 'once' => [ 5.008, DEFAULT_OFF],
68 'misc' => [ 5.008, DEFAULT_OFF],
69 'regexp' => [ 5.008, DEFAULT_OFF],
70 'glob' => [ 5.008, DEFAULT_ON],
71 'untie' => [ 5.008, DEFAULT_OFF],
72 'substr' => [ 5.008, DEFAULT_OFF],
73 'taint' => [ 5.008, DEFAULT_OFF],
74 'signal' => [ 5.008, DEFAULT_OFF],
75 'closure' => [ 5.008, DEFAULT_OFF],
76 'overflow' => [ 5.008, DEFAULT_OFF],
77 'portable' => [ 5.008, DEFAULT_OFF],
79 'surrogate' => [ 5.013, DEFAULT_OFF],
80 'nonchar' => [ 5.013, DEFAULT_OFF],
81 'non_unicode' => [ 5.013, DEFAULT_OFF],
83 'exiting' => [ 5.008, DEFAULT_OFF],
84 'pack' => [ 5.008, DEFAULT_OFF],
85 'unpack' => [ 5.008, DEFAULT_OFF],
86 'threads' => [ 5.008, DEFAULT_OFF],
87 'imprecision' => [ 5.011, DEFAULT_OFF],
88 'experimental' => [ 5.017, {
89 'experimental::lexical_subs' =>
90 [ 5.017, DEFAULT_ON ],
91 'experimental::regex_sets' =>
92 [ 5.017, DEFAULT_ON ],
93 'experimental::lexical_topic' =>
94 [ 5.017, DEFAULT_ON ],
95 'experimental::smartmatch' =>
96 [ 5.017, DEFAULT_ON ],
97 'experimental::postderef' =>
98 [ 5.019, DEFAULT_ON ],
99 'experimental::autoderef' =>
100 [ 5.019, DEFAULT_ON ],
101 'experimental::signatures' =>
102 [ 5.019, DEFAULT_ON ],
103 'experimental::win32_perlio' =>
104 [ 5.021, DEFAULT_ON ],
107 'missing' => [ 5.021, DEFAULT_OFF],
108 'redundant' => [ 5.021, DEFAULT_OFF],
110 #'default' => [ 5.008, DEFAULT_ON ],
128 foreach $k (sort keys %$tre) {
130 die "duplicate key $k\n" if defined $list{$k} ;
131 die "Value associated with key '$k' is not an ARRAY reference"
132 if !ref $v || ref $v ne 'ARRAY' ;
134 my ($ver, $rest) = @{ $v } ;
135 push @{ $v_list{$ver} }, $k;
138 { valueWalk ($rest) }
147 foreach my $ver ( sort { $a <=> $b } keys %v_list ) {
148 foreach my $name (@{ $v_list{$ver} } ) {
149 $ValueToName{ $index } = [ uc $name, $ver ] ;
150 $NameToValue{ uc $name } = $index ++ ;
157 ###########################################################################
165 foreach $k (sort keys %$tre) {
167 die "duplicate key $k\n" if defined $list{$k} ;
168 die "Can't find key '$k'"
169 if ! defined $NameToValue{uc $k} ;
170 push @{ $list{$k} }, $NameToValue{uc $k} ;
171 die "Value associated with key '$k' is not an ARRAY reference"
172 if !ref $v || ref $v ne 'ARRAY' ;
174 my ($ver, $rest) = @{ $v } ;
176 { push (@{ $list{$k} }, walk ($rest)) }
177 elsif ($rest == DEFAULT_ON)
178 { push @def, $NameToValue{uc $k} }
180 push @list, @{ $list{$k} } ;
186 ###########################################################################
193 for my $i (1 .. @a - 1) {
195 if $a[$i] == $a[$i - 1] + 1
196 && ($i >= @a - 1 || $a[$i] + 1 == $a[$i + 1] );
198 $out[-1] = $a[-1] if $out[-1] eq "..";
200 my $out = join(",",@out);
202 $out =~ s/,(\.\.,)+/../g ;
206 ###########################################################################
213 my $max = (sort {$a <=> $b} map { length $_ } keys %$tre)[-1] ;
214 my @keys = sort keys %$tre ;
218 while ($k = shift @keys) {
220 die "Value associated with key '$k' is not an ARRAY reference"
221 if !ref $v || ref $v ne 'ARRAY' ;
225 $rv .= $prefix . "|\n" ;
226 $rv .= $prefix . "+- $k" ;
227 $offset = ' ' x ($max + 4) ;
230 $rv .= $prefix . "$k" ;
231 $offset = ' ' x ($max + 1) ;
234 my ($ver, $rest) = @{ $v } ;
237 my $bar = @keys ? "|" : " ";
238 $rv .= " -" . "-" x ($max - length $k ) . "+\n" ;
239 $rv .= warningsTree ($rest, $prefix . $bar . $offset )
248 ###########################################################################
252 my ($f, $max, @a) = @_ ;
253 my $mask = "\x00" x $max ;
257 vec($mask, $_, 1) = 1 ;
260 foreach (unpack("C*", $mask)) {
262 $string .= '\x' . sprintf("%2.2x", $_)
265 $string .= '\\' . sprintf("%o", $_)
274 return mkHexOct("x", $max, @a);
280 return mkHexOct("o", $max, @a);
283 ###########################################################################
285 if (@ARGV && $ARGV[0] eq "tree")
287 print warningsTree($tree, " ") ;
291 my ($warn, $pm) = map {
292 open_new($_, '>', { by => 'regen/warnings.pl' });
293 } 'warnings.h', 'lib/warnings.pm';
295 my ($index, $warn_size);
298 # generate warnings.h
302 #define Off(x) ((x) / 8)
303 #define Bit(x) (1 << ((x) % 8))
304 #define IsSet(a, x) ((a)[Off(x)] & Bit(x))
307 #define G_WARN_OFF 0 /* $^W == 0 */
308 #define G_WARN_ON 1 /* -w flag and $^W != 0 */
309 #define G_WARN_ALL_ON 2 /* -W flag */
310 #define G_WARN_ALL_OFF 4 /* -X flag */
311 #define G_WARN_ONCE 8 /* set if 'once' ever enabled */
312 #define G_WARN_ALL_MASK (G_WARN_ALL_ON|G_WARN_ALL_OFF)
314 #define pWARN_STD NULL
315 #define pWARN_ALL (((STRLEN*)0)+1) /* use warnings 'all' */
316 #define pWARN_NONE (((STRLEN*)0)+2) /* no warnings 'all' */
318 #define specialWARN(x) ((x) == pWARN_STD || (x) == pWARN_ALL || \
321 /* if PL_warnhook is set to this value, then warnings die */
322 #define PERL_WARNHOOK_FATAL (&PL_sv_placeholder)
328 $index = orderValues();
330 die <<EOM if $index > 255 ;
331 Too many warnings categories -- max is 255
332 rewrite packWARN* & unpackWARN* macros
338 $warn_size = int($index / 8) + ($index % 8 != 0) ;
342 foreach $k (sort { $a <=> $b } keys %ValueToName) {
343 my ($name, $version) = @{ $ValueToName{$k} };
344 print $warn "\n/* Warnings Categories added in Perl $version */\n\n"
345 if $last_ver != $version ;
347 print $warn tab(5, "#define WARN_$name"), " $k\n" ;
348 $last_ver = $version ;
352 print $warn tab(5, '#define WARNsize'), "$warn_size\n" ;
353 print $warn tab(5, '#define WARN_ALLstring'), '"', ('\125' x $warn_size) , "\"\n" ;
354 print $warn tab(5, '#define WARN_NONEstring'), '"', ('\0' x $warn_size) , "\"\n" ;
358 #define isLEXWARN_on (PL_curcop->cop_warnings != pWARN_STD)
359 #define isLEXWARN_off (PL_curcop->cop_warnings == pWARN_STD)
360 #define isWARN_ONCE (PL_dowarn & (G_WARN_ON|G_WARN_ONCE))
361 #define isWARN_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)))
362 #define isWARNf_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)+1))
364 #define DUP_WARNINGS(p) \
365 (specialWARN(p) ? (STRLEN*)(p) \
366 : (STRLEN*)CopyD(p, PerlMemShared_malloc(sizeof(*p)+*p), sizeof(*p)+*p, \
369 #define ckWARN(w) Perl_ckwarn(aTHX_ packWARN(w))
371 /* The w1, w2 ... should be independent warnings categories; one shouldn't be
372 * a subcategory of any other */
374 #define ckWARN2(w1,w2) Perl_ckwarn(aTHX_ packWARN2(w1,w2))
375 #define ckWARN3(w1,w2,w3) Perl_ckwarn(aTHX_ packWARN3(w1,w2,w3))
376 #define ckWARN4(w1,w2,w3,w4) Perl_ckwarn(aTHX_ packWARN4(w1,w2,w3,w4))
378 #define ckWARN_d(w) Perl_ckwarn_d(aTHX_ packWARN(w))
379 #define ckWARN2_d(w1,w2) Perl_ckwarn_d(aTHX_ packWARN2(w1,w2))
380 #define ckWARN3_d(w1,w2,w3) Perl_ckwarn_d(aTHX_ packWARN3(w1,w2,w3))
381 #define ckWARN4_d(w1,w2,w3,w4) Perl_ckwarn_d(aTHX_ packWARN4(w1,w2,w3,w4))
385 #define packWARN(a) (a )
387 /* The a, b, ... should be independent warnings categories; one shouldn't be
388 * a subcategory of any other */
390 #define packWARN2(a,b) ((a) | ((b)<<8) )
391 #define packWARN3(a,b,c) ((a) | ((b)<<8) | ((c)<<16) )
392 #define packWARN4(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((d) <<24))
394 #define unpackWARN1(x) ((x) & 0xFF)
395 #define unpackWARN2(x) (((x) >>8) & 0xFF)
396 #define unpackWARN3(x) (((x) >>16) & 0xFF)
397 #define unpackWARN4(x) (((x) >>24) & 0xFF)
400 ( ! specialWARN(PL_curcop->cop_warnings) && \
401 ( isWARNf_on(PL_curcop->cop_warnings, WARN_ALL) || \
402 isWARNf_on(PL_curcop->cop_warnings, unpackWARN1(x)) || \
403 isWARNf_on(PL_curcop->cop_warnings, unpackWARN2(x)) || \
404 isWARNf_on(PL_curcop->cop_warnings, unpackWARN3(x)) || \
405 isWARNf_on(PL_curcop->cop_warnings, unpackWARN4(x))))
407 /* end of file warnings.h */
410 read_only_bottom_close_and_rename($warn);
414 last if /^KEYWORDS$/ ;
415 if ($_ eq "=for warnings.pl tree-goes-here\n") {
416 print $pm warningsTree($tree, " ");
423 print $pm "our %Offsets = (\n" ;
424 foreach my $k (sort { $a <=> $b } keys %ValueToName) {
425 my ($name, $version) = @{ $ValueToName{$k} };
428 if ( $last_ver != $version ) {
430 print $pm tab(4, " # Warnings Categories added in Perl $version");
433 print $pm tab(4, " '$name'"), "=> $k,\n" ;
434 $last_ver = $version;
437 print $pm " );\n\n" ;
439 print $pm "our %Bits = (\n" ;
440 foreach my $k (sort keys %list) {
443 my @list = sort { $a <=> $b } @$v ;
445 print $pm tab(4, " '$k'"), '=> "',
446 mkHex($warn_size, map $_ * 2 , @list),
447 '", # [', mkRange(@list), "]\n" ;
450 print $pm " );\n\n" ;
452 print $pm "our %DeadBits = (\n" ;
453 foreach my $k (sort keys %list) {
456 my @list = sort { $a <=> $b } @$v ;
458 print $pm tab(4, " '$k'"), '=> "',
459 mkHex($warn_size, map $_ * 2 + 1 , @list),
460 '", # [', mkRange(@list), "]\n" ;
463 print $pm " );\n\n" ;
464 print $pm '$NONE = "', ('\0' x $warn_size) , "\";\n" ;
465 print $pm '$DEFAULT = "', mkHex($warn_size, map $_ * 2, @def),
466 '", # [', mkRange(@def), "]\n" ;
467 print $pm '$LAST_BIT = ' . "$index ;\n" ;
468 print $pm '$BYTES = ' . "$warn_size ;\n" ;
473 read_only_bottom_close_and_rename($pm);
478 our $VERSION = '1.26';
480 # Verify that we're called correctly so that warnings will work.
481 # see also strict.pm.
482 unless ( __FILE__ =~ /(^|[\/\\])\Q${\__PACKAGE__}\E\.pmc?$/ ) {
483 my (undef, $f, $l) = caller;
484 die("Incorrect use of pragma '${\__PACKAGE__}' at $f line $l.\n");
489 warnings - Perl pragma to control optional warnings
499 use warnings::register;
500 if (warnings::enabled()) {
501 warnings::warn("some warning");
504 if (warnings::enabled("void")) {
505 warnings::warn("void", "some warning");
508 if (warnings::enabled($object)) {
509 warnings::warn($object, "some warning");
512 warnings::warnif("some warning");
513 warnings::warnif("void", "some warning");
514 warnings::warnif($object, "some warning");
518 The C<warnings> pragma gives control over which warnings are enabled in
519 which parts of a Perl program. It's a more flexible alternative for
520 both the command line flag B<-w> and the equivalent Perl variable,
523 This pragma works just like the C<strict> pragma.
524 This means that the scope of the warning pragma is limited to the
525 enclosing block. It also means that the pragma setting will not
526 leak across files (via C<use>, C<require> or C<do>). This allows
527 authors to independently define the degree of warning checks that will
528 be applied to their module.
530 By default, optional warnings are disabled, so any legacy code that
531 doesn't attempt to control the warnings will work unchanged.
533 All warnings are enabled in a block by either of these:
538 Similarly all warnings are disabled in a block by either of these:
543 For example, consider the code below:
553 The code in the enclosing block has warnings enabled, but the inner
554 block has them disabled. In this case that means the assignment to the
555 scalar C<$c> will trip the C<"Scalar value @a[0] better written as $a[0]">
556 warning, but the assignment to the scalar C<$b> will not.
558 =head2 Default Warnings and Optional Warnings
560 Before the introduction of lexical warnings, Perl had two classes of
561 warnings: mandatory and optional.
563 As its name suggests, if your code tripped a mandatory warning, you
564 would get a warning whether you wanted it or not.
565 For example, the code below would always produce an C<"isn't numeric">
566 warning about the "2:".
570 With the introduction of lexical warnings, mandatory warnings now become
571 I<default> warnings. The difference is that although the previously
572 mandatory warnings are still enabled by default, they can then be
573 subsequently enabled or disabled with the lexical warning pragma. For
574 example, in the code below, an C<"isn't numeric"> warning will only
575 be reported for the C<$a> variable.
581 Note that neither the B<-w> flag or the C<$^W> can be used to
582 disable/enable default warnings. They are still mandatory in this case.
584 =head2 What's wrong with B<-w> and C<$^W>
586 Although very useful, the big problem with using B<-w> on the command
587 line to enable warnings is that it is all or nothing. Take the typical
588 scenario when you are writing a Perl program. Parts of the code you
589 will write yourself, but it's very likely that you will make use of
590 pre-written Perl modules. If you use the B<-w> flag in this case, you
591 end up enabling warnings in pieces of code that you haven't written.
593 Similarly, using C<$^W> to either disable or enable blocks of code is
594 fundamentally flawed. For a start, say you want to disable warnings in
595 a block of code. You might expect this to be enough to do the trick:
603 When this code is run with the B<-w> flag, a warning will be produced
604 for the C<$a> line: C<"Reversed += operator">.
606 The problem is that Perl has both compile-time and run-time warnings. To
607 disable compile-time warnings you need to rewrite the code like this:
615 The other big problem with C<$^W> is the way you can inadvertently
616 change the warning setting in unexpected places in your code. For example,
617 when the code below is run (without the B<-w> flag), the second call
618 to C<doit> will trip a C<"Use of uninitialized value"> warning, whereas
633 This is a side-effect of C<$^W> being dynamically scoped.
635 Lexical warnings get around these limitations by allowing finer control
636 over where warnings can or can't be tripped.
638 =head2 Controlling Warnings from the Command Line
640 There are three Command Line flags that can be used to control when
641 warnings are (or aren't) produced:
648 This is the existing flag. If the lexical warnings pragma is B<not>
649 used in any of you code, or any of the modules that you use, this flag
650 will enable warnings everywhere. See L<Backward Compatibility> for
651 details of how this flag interacts with lexical warnings.
656 If the B<-W> flag is used on the command line, it will enable all warnings
657 throughout the program regardless of whether warnings were disabled
658 locally using C<no warnings> or C<$^W =0>.
659 This includes all files that get
660 included via C<use>, C<require> or C<do>.
661 Think of it as the Perl equivalent of the "lint" command.
666 Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.
670 =head2 Backward Compatibility
672 If you are used to working with a version of Perl prior to the
673 introduction of lexically scoped warnings, or have code that uses both
674 lexical warnings and C<$^W>, this section will describe how they interact.
676 How Lexical Warnings interact with B<-w>/C<$^W>:
682 If none of the three command line flags (B<-w>, B<-W> or B<-X>) that
683 control warnings is used and neither C<$^W> nor the C<warnings> pragma
684 are used, then default warnings will be enabled and optional warnings
686 This means that legacy code that doesn't attempt to control the warnings
691 The B<-w> flag just sets the global C<$^W> variable as in 5.005. This
692 means that any legacy code that currently relies on manipulating C<$^W>
693 to control warning behavior will still work as is.
697 Apart from now being a boolean, the C<$^W> variable operates in exactly
698 the same horrible uncontrolled global way, except that it cannot
699 disable/enable default warnings.
703 If a piece of code is under the control of the C<warnings> pragma,
704 both the C<$^W> variable and the B<-w> flag will be ignored for the
705 scope of the lexical warning.
709 The only way to override a lexical warnings setting is with the B<-W>
710 or B<-X> command line flags.
714 The combined effect of 3 & 4 is that it will allow code which uses
715 the C<warnings> pragma to control the warning behavior of $^W-type
716 code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
718 =head2 Category Hierarchy
719 X<warning, categories>
721 A hierarchy of "categories" have been defined to allow groups of warnings
722 to be enabled/disabled in isolation.
724 The current hierarchy is:
726 =for warnings.pl tree-goes-here
728 Just like the "strict" pragma any of these categories can be combined
730 use warnings qw(void redefine);
731 no warnings qw(io syntax untie);
733 Also like the "strict" pragma, if there is more than one instance of the
734 C<warnings> pragma in a given scope the cumulative effect is additive.
736 use warnings qw(void); # only "void" warnings enabled
738 use warnings qw(io); # only "void" & "io" warnings enabled
740 no warnings qw(void); # only "io" warnings enabled
742 To determine which category a specific warning has been assigned to see
745 Note: Before Perl 5.8.0, the lexical warnings category "deprecated" was a
746 sub-category of the "syntax" category. It is now a top-level category
749 Note: Before 5.21.0, the "missing" lexical warnings category was
750 internally defined to be the same as the "uninitialized" category. It
751 is now a top-level category in its own right.
753 =head2 Fatal Warnings
756 The presence of the word "FATAL" in the category list will escalate any
757 warnings detected from the categories specified in the lexical scope
758 into fatal errors. In the code below, the use of C<time>, C<length>
759 and C<join> can all produce a C<"Useless use of xxx in void context">
767 use warnings FATAL => qw(void);
775 When run it produces this output
777 Useless use of time in void context at fatal line 3.
778 Useless use of length in void context at fatal line 7.
780 The scope where C<length> is used has escalated the C<void> warnings
781 category into a fatal error, so the program terminates immediately when it
782 encounters the warning.
784 To explicitly turn off a "FATAL" warning you just disable the warning
785 it is associated with. So, for example, to disable the "void" warning
786 in the example above, either of these will do the trick:
788 no warnings qw(void);
789 no warnings FATAL => qw(void);
791 If you want to downgrade a warning that has been escalated into a fatal
792 error back to a normal warning, you can use the "NONFATAL" keyword. For
793 example, the code below will promote all warnings into fatal errors,
794 except for those in the "syntax" category.
796 use warnings FATAL => 'all', NONFATAL => 'syntax';
798 As of Perl 5.20, instead of C<< use warnings FATAL => 'all'; >> you can
801 use v5.20; # Perl 5.20 or greater is required for the following
802 use warnings 'FATAL'; # short form of "use warnings FATAL => 'all';"
804 If you want your program to be compatible with versions of Perl before
805 5.20, you must use C<< use warnings FATAL => 'all'; >> instead. (In
806 previous versions of Perl, the behavior of the statements
807 C<< use warnings 'FATAL'; >>, C<< use warnings 'NONFATAL'; >> and
808 C<< no warnings 'FATAL'; >> was unspecified; they did not behave as if
809 they included the C<< => 'all' >> portion. As of 5.20, they do.)
811 B<NOTE:> Users of FATAL warnings, especially
812 those using C<< FATAL => 'all' >>
813 should be fully aware that they are risking future portability of their
814 programs by doing so. Perl makes absolutely no commitments to not
815 introduce new warnings, or warnings categories in the future, and indeed
816 we explicitly reserve the right to do so. Code that may not warn now may
817 warn in a future release of Perl if the Perl5 development team deems it
818 in the best interests of the community to do so. Should code using FATAL
819 warnings break due to the introduction of a new warning we will NOT
820 consider it an incompatible change. Users of FATAL warnings should take
821 special caution during upgrades to check to see if their code triggers
822 any new warnings and should pay particular attention to the fine print of
823 the documentation of the features they use to ensure they do not exploit
824 features that are documented as risky, deprecated, or unspecified, or where
825 the documentation says "so don't do that", or anything with the same sense
826 and spirit. Use of such features in combination with FATAL warnings is
827 ENTIRELY AT THE USER'S RISK.
829 =head2 Reporting Warnings from a Module
830 X<warning, reporting> X<warning, registering>
832 The C<warnings> pragma provides a number of functions that are useful for
833 module authors. These are used when you want to report a module-specific
834 warning to a calling module has enabled warnings via the C<warnings>
837 Consider the module C<MyMod::Abc> below.
841 use warnings::register;
845 if ($path !~ m#^/#) {
846 warnings::warn("changing relative path to /var/abc")
847 if warnings::enabled();
848 $path = "/var/abc/$path";
854 The call to C<warnings::register> will create a new warnings category
855 called "MyMod::Abc", i.e. the new category name matches the current
856 package name. The C<open> function in the module will display a warning
857 message if it gets given a relative path as a parameter. This warnings
858 will only be displayed if the code that uses C<MyMod::Abc> has actually
859 enabled them with the C<warnings> pragma like below.
862 use warnings 'MyMod::Abc';
864 abc::open("../fred.txt");
866 It is also possible to test whether the pre-defined warnings categories are
867 set in the calling module with the C<warnings::enabled> function. Consider
868 this snippet of code:
873 warnings::warnif("deprecated",
874 "open is deprecated, use new instead");
882 The function C<open> has been deprecated, so code has been included to
883 display a warning message whenever the calling module has (at least) the
884 "deprecated" warnings category enabled. Something like this, say.
886 use warnings 'deprecated';
889 MyMod::Abc::open($filename);
891 Either the C<warnings::warn> or C<warnings::warnif> function should be
892 used to actually display the warnings message. This is because they can
893 make use of the feature that allows warnings to be escalated into fatal
894 errors. So in this case
897 use warnings FATAL => 'MyMod::Abc';
899 MyMod::Abc::open('../fred.txt');
901 the C<warnings::warnif> function will detect this and die after
902 displaying the warning message.
904 The three warnings functions, C<warnings::warn>, C<warnings::warnif>
905 and C<warnings::enabled> can optionally take an object reference in place
906 of a category name. In this case the functions will use the class name
907 of the object as the warnings category.
909 Consider this example:
914 use warnings::register;
927 if ($value % 2 && warnings::enabled($self))
928 { warnings::warn($self, "Odd numbers are unsafe") }
935 $self->check($value);
943 use warnings::register;
945 our @ISA = qw( Original );
955 The code below makes use of both modules, but it only enables warnings from
960 use warnings 'Derived';
961 my $a = Original->new();
963 my $b = Derived->new();
966 When this code is run only the C<Derived> object, C<$b>, will generate
969 Odd numbers are unsafe at main.pl line 7
971 Notice also that the warning is reported at the line where the object is first
974 When registering new categories of warning, you can supply more names to
975 warnings::register like this:
978 use warnings::register qw(format precision);
982 warnings::warnif('MyModule::format', '...');
988 =item use warnings::register
990 Creates a new warnings category with the same name as the package where
991 the call to the pragma is used.
993 =item warnings::enabled()
995 Use the warnings category with the same name as the current package.
997 Return TRUE if that warnings category is enabled in the calling module.
998 Otherwise returns FALSE.
1000 =item warnings::enabled($category)
1002 Return TRUE if the warnings category, C<$category>, is enabled in the
1004 Otherwise returns FALSE.
1006 =item warnings::enabled($object)
1008 Use the name of the class for the object reference, C<$object>, as the
1011 Return TRUE if that warnings category is enabled in the first scope
1012 where the object is used.
1013 Otherwise returns FALSE.
1015 =item warnings::fatal_enabled()
1017 Return TRUE if the warnings category with the same name as the current
1018 package has been set to FATAL in the calling module.
1019 Otherwise returns FALSE.
1021 =item warnings::fatal_enabled($category)
1023 Return TRUE if the warnings category C<$category> has been set to FATAL in
1025 Otherwise returns FALSE.
1027 =item warnings::fatal_enabled($object)
1029 Use the name of the class for the object reference, C<$object>, as the
1032 Return TRUE if that warnings category has been set to FATAL in the first
1033 scope where the object is used.
1034 Otherwise returns FALSE.
1036 =item warnings::warn($message)
1038 Print C<$message> to STDERR.
1040 Use the warnings category with the same name as the current package.
1042 If that warnings category has been set to "FATAL" in the calling module
1043 then die. Otherwise return.
1045 =item warnings::warn($category, $message)
1047 Print C<$message> to STDERR.
1049 If the warnings category, C<$category>, has been set to "FATAL" in the
1050 calling module then die. Otherwise return.
1052 =item warnings::warn($object, $message)
1054 Print C<$message> to STDERR.
1056 Use the name of the class for the object reference, C<$object>, as the
1059 If that warnings category has been set to "FATAL" in the scope where C<$object>
1060 is first used then die. Otherwise return.
1063 =item warnings::warnif($message)
1067 if (warnings::enabled())
1068 { warnings::warn($message) }
1070 =item warnings::warnif($category, $message)
1074 if (warnings::enabled($category))
1075 { warnings::warn($category, $message) }
1077 =item warnings::warnif($object, $message)
1081 if (warnings::enabled($object))
1082 { warnings::warn($object, $message) }
1084 =item warnings::register_categories(@names)
1086 This registers warning categories for the given names and is primarily for
1087 use by the warnings::register pragma.
1091 See also L<perlmodlib/Pragmatic Modules> and L<perldiag>.
1097 $All = "" ; vec($All, $Offsets{'all'}, 2) = 3 ;
1101 require Carp; # this initializes %CarpInternal
1102 local $Carp::CarpInternal{'warnings'};
1103 delete $Carp::CarpInternal{'warnings'};
1113 foreach my $word ( @_ ) {
1114 if ($word eq 'FATAL') {
1118 elsif ($word eq 'NONFATAL') {
1122 elsif ($catmask = $Bits{$word}) {
1124 $mask |= $DeadBits{$word} if $fatal ;
1125 $mask &= ~($DeadBits{$word}|$All) if $no_fatal ;
1128 { Croaker("Unknown warnings category '$word'")}
1136 # called from B::Deparse.pm
1137 push @_, 'all' unless @_ ;
1138 return _bits(undef, @_) ;
1145 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
1147 if (vec($mask, $Offsets{'all'}, 1)) {
1148 $mask |= $Bits{'all'} ;
1149 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
1152 # append 'all' when implied (after a lone "FATAL" or "NONFATAL")
1153 push @_, 'all' if @_==1 && ( $_[0] eq 'FATAL' || $_[0] eq 'NONFATAL' );
1155 # Empty @_ is equivalent to @_ = 'all' ;
1156 ${^WARNING_BITS} = @_ ? _bits($mask, @_) : $mask | $Bits{all} ;
1164 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
1166 if (vec($mask, $Offsets{'all'}, 1)) {
1167 $mask |= $Bits{'all'} ;
1168 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
1171 # append 'all' when implied (empty import list or after a lone "FATAL")
1172 push @_, 'all' if !@_ || @_==1 && $_[0] eq 'FATAL';
1174 foreach my $word ( @_ ) {
1175 if ($word eq 'FATAL') {
1178 elsif ($catmask = $Bits{$word}) {
1179 $mask &= ~($catmask | $DeadBits{$word} | $All);
1182 { Croaker("Unknown warnings category '$word'")}
1185 ${^WARNING_BITS} = $mask ;
1188 my %builtin_type; @builtin_type{qw(SCALAR ARRAY HASH CODE REF GLOB LVALUE Regexp)} = ();
1190 sub MESSAGE () { 4 };
1192 sub NORMAL () { 1 };
1200 my $has_message = $wanted & MESSAGE;
1202 unless (@_ == 1 || @_ == ($has_message ? 2 : 0)) {
1203 my $sub = (caller 1)[3];
1204 my $syntax = $has_message ? "[category,] 'message'" : '[category]';
1205 Croaker("Usage: $sub($syntax)");
1208 my $message = pop if $has_message;
1211 # check the category supplied.
1213 if (my $type = ref $category) {
1214 Croaker("not an object")
1215 if exists $builtin_type{$type};
1219 $offset = $Offsets{$category};
1220 Croaker("Unknown warnings category '$category'")
1221 unless defined $offset;
1224 $category = (caller(1))[0] ;
1225 $offset = $Offsets{$category};
1226 Croaker("package '$category' not registered for warnings")
1227 unless defined $offset ;
1235 while (do { { package DB; $pkg = (caller($i++))[0] } } ) {
1236 last unless @DB::args && $DB::args[0] =~ /^$category=/ ;
1241 $i = _error_loc(); # see where Carp will allocate the error
1244 # Default to 0 if caller returns nothing. Default to $DEFAULT if it
1245 # explicitly returns undef.
1246 my(@callers_bitmask) = (caller($i))[9] ;
1247 my $callers_bitmask =
1248 @callers_bitmask ? $callers_bitmask[0] // $DEFAULT : 0 ;
1251 foreach my $type (FATAL, NORMAL) {
1252 next unless $wanted & $type;
1254 push @results, (vec($callers_bitmask, $offset + $type - 1, 1) ||
1255 vec($callers_bitmask, $Offsets{'all'} + $type - 1, 1));
1258 # &enabled and &fatal_enabled
1259 return $results[0] unless $has_message;
1261 # &warnif, and the category is neither enabled as warning nor as fatal
1262 return if $wanted == (NORMAL | FATAL | MESSAGE)
1263 && !($results[0] || $results[1]);
1266 Carp::croak($message) if $results[0];
1267 # will always get here for &warn. will only get here for &warnif if the
1268 # category is enabled
1269 Carp::carp($message);
1277 vec($mask, $bit, 1) = 1;
1281 sub register_categories
1285 for my $name (@names) {
1286 if (! defined $Bits{$name}) {
1287 $Bits{$name} = _mkMask($LAST_BIT);
1288 vec($Bits{'all'}, $LAST_BIT, 1) = 1;
1289 $Offsets{$name} = $LAST_BIT ++;
1290 foreach my $k (keys %Bits) {
1291 vec($Bits{$k}, $LAST_BIT, 1) = 0;
1293 $DeadBits{$name} = _mkMask($LAST_BIT);
1294 vec($DeadBits{'all'}, $LAST_BIT++, 1) = 1;
1301 goto &Carp::short_error_loc; # don't introduce another stack frame
1306 return __chk(NORMAL, @_);
1311 return __chk(FATAL, @_);
1316 return __chk(FATAL | MESSAGE, @_);
1321 return __chk(NORMAL | FATAL | MESSAGE, @_);
1324 # These are not part of any public interface, so we can delete them to save
1326 delete @warnings::{qw(NORMAL FATAL MESSAGE)};