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 #'default' => [ 5.008, DEFAULT_ON ],
125 foreach $k (sort keys %$tre) {
127 die "duplicate key $k\n" if defined $list{$k} ;
128 die "Value associated with key '$k' is not an ARRAY reference"
129 if !ref $v || ref $v ne 'ARRAY' ;
131 my ($ver, $rest) = @{ $v } ;
132 push @{ $v_list{$ver} }, $k;
135 { valueWalk ($rest) }
144 foreach my $ver ( sort { $a <=> $b } keys %v_list ) {
145 foreach my $name (@{ $v_list{$ver} } ) {
146 $ValueToName{ $index } = [ uc $name, $ver ] ;
147 $NameToValue{ uc $name } = $index ++ ;
154 ###########################################################################
162 foreach $k (sort keys %$tre) {
164 die "duplicate key $k\n" if defined $list{$k} ;
165 die "Can't find key '$k'"
166 if ! defined $NameToValue{uc $k} ;
167 push @{ $list{$k} }, $NameToValue{uc $k} ;
168 die "Value associated with key '$k' is not an ARRAY reference"
169 if !ref $v || ref $v ne 'ARRAY' ;
171 my ($ver, $rest) = @{ $v } ;
173 { push (@{ $list{$k} }, walk ($rest)) }
174 elsif ($rest == DEFAULT_ON)
175 { push @def, $NameToValue{uc $k} }
177 push @list, @{ $list{$k} } ;
183 ###########################################################################
190 for my $i (1 .. @a - 1) {
192 if $a[$i] == $a[$i - 1] + 1
193 && ($i >= @a - 1 || $a[$i] + 1 == $a[$i + 1] );
195 $out[-1] = $a[-1] if $out[-1] eq "..";
197 my $out = join(",",@out);
199 $out =~ s/,(\.\.,)+/../g ;
203 ###########################################################################
210 my $max = (sort {$a <=> $b} map { length $_ } keys %$tre)[-1] ;
211 my @keys = sort keys %$tre ;
215 while ($k = shift @keys) {
217 die "Value associated with key '$k' is not an ARRAY reference"
218 if !ref $v || ref $v ne 'ARRAY' ;
222 $rv .= $prefix . "|\n" ;
223 $rv .= $prefix . "+- $k" ;
224 $offset = ' ' x ($max + 4) ;
227 $rv .= $prefix . "$k" ;
228 $offset = ' ' x ($max + 1) ;
231 my ($ver, $rest) = @{ $v } ;
234 my $bar = @keys ? "|" : " ";
235 $rv .= " -" . "-" x ($max - length $k ) . "+\n" ;
236 $rv .= warningsTree ($rest, $prefix . $bar . $offset )
245 ###########################################################################
249 my ($f, $max, @a) = @_ ;
250 my $mask = "\x00" x $max ;
254 vec($mask, $_, 1) = 1 ;
257 foreach (unpack("C*", $mask)) {
259 $string .= '\x' . sprintf("%2.2x", $_)
262 $string .= '\\' . sprintf("%o", $_)
271 return mkHexOct("x", $max, @a);
277 return mkHexOct("o", $max, @a);
280 ###########################################################################
282 if (@ARGV && $ARGV[0] eq "tree")
284 print warningsTree($tree, " ") ;
288 my ($warn, $pm) = map {
289 open_new($_, '>', { by => 'regen/warnings.pl' });
290 } 'warnings.h', 'lib/warnings.pm';
292 my ($index, $warn_size);
295 # generate warnings.h
299 #define Off(x) ((x) / 8)
300 #define Bit(x) (1 << ((x) % 8))
301 #define IsSet(a, x) ((a)[Off(x)] & Bit(x))
304 #define G_WARN_OFF 0 /* $^W == 0 */
305 #define G_WARN_ON 1 /* -w flag and $^W != 0 */
306 #define G_WARN_ALL_ON 2 /* -W flag */
307 #define G_WARN_ALL_OFF 4 /* -X flag */
308 #define G_WARN_ONCE 8 /* set if 'once' ever enabled */
309 #define G_WARN_ALL_MASK (G_WARN_ALL_ON|G_WARN_ALL_OFF)
311 #define pWARN_STD NULL
312 #define pWARN_ALL (((STRLEN*)0)+1) /* use warnings 'all' */
313 #define pWARN_NONE (((STRLEN*)0)+2) /* no warnings 'all' */
315 #define specialWARN(x) ((x) == pWARN_STD || (x) == pWARN_ALL || \
318 /* if PL_warnhook is set to this value, then warnings die */
319 #define PERL_WARNHOOK_FATAL (&PL_sv_placeholder)
325 $index = orderValues();
327 die <<EOM if $index > 255 ;
328 Too many warnings categories -- max is 255
329 rewrite packWARN* & unpackWARN* macros
335 $warn_size = int($index / 8) + ($index % 8 != 0) ;
339 foreach $k (sort { $a <=> $b } keys %ValueToName) {
340 my ($name, $version) = @{ $ValueToName{$k} };
341 print $warn "\n/* Warnings Categories added in Perl $version */\n\n"
342 if $last_ver != $version ;
344 print $warn tab(5, "#define WARN_$name"), " $k\n" ;
345 $last_ver = $version ;
349 print $warn tab(5, '#define WARNsize'), "$warn_size\n" ;
350 print $warn tab(5, '#define WARN_ALLstring'), '"', ('\125' x $warn_size) , "\"\n" ;
351 print $warn tab(5, '#define WARN_NONEstring'), '"', ('\0' x $warn_size) , "\"\n" ;
355 #define isLEXWARN_on (PL_curcop->cop_warnings != pWARN_STD)
356 #define isLEXWARN_off (PL_curcop->cop_warnings == pWARN_STD)
357 #define isWARN_ONCE (PL_dowarn & (G_WARN_ON|G_WARN_ONCE))
358 #define isWARN_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)))
359 #define isWARNf_on(c,x) (IsSet((U8 *)(c + 1), 2*(x)+1))
361 #define DUP_WARNINGS(p) \
362 (specialWARN(p) ? (STRLEN*)(p) \
363 : (STRLEN*)CopyD(p, PerlMemShared_malloc(sizeof(*p)+*p), sizeof(*p)+*p, \
366 #define ckWARN(w) Perl_ckwarn(aTHX_ packWARN(w))
368 /* The w1, w2 ... should be independent warnings categories; one shouldn't be
369 * a subcategory of any other */
371 #define ckWARN2(w1,w2) Perl_ckwarn(aTHX_ packWARN2(w1,w2))
372 #define ckWARN3(w1,w2,w3) Perl_ckwarn(aTHX_ packWARN3(w1,w2,w3))
373 #define ckWARN4(w1,w2,w3,w4) Perl_ckwarn(aTHX_ packWARN4(w1,w2,w3,w4))
375 #define ckWARN_d(w) Perl_ckwarn_d(aTHX_ packWARN(w))
376 #define ckWARN2_d(w1,w2) Perl_ckwarn_d(aTHX_ packWARN2(w1,w2))
377 #define ckWARN3_d(w1,w2,w3) Perl_ckwarn_d(aTHX_ packWARN3(w1,w2,w3))
378 #define ckWARN4_d(w1,w2,w3,w4) Perl_ckwarn_d(aTHX_ packWARN4(w1,w2,w3,w4))
382 #define packWARN(a) (a )
384 /* The a, b, ... should be independent warnings categories; one shouldn't be
385 * a subcategory of any other */
387 #define packWARN2(a,b) ((a) | ((b)<<8) )
388 #define packWARN3(a,b,c) ((a) | ((b)<<8) | ((c)<<16) )
389 #define packWARN4(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((d) <<24))
391 #define unpackWARN1(x) ((x) & 0xFF)
392 #define unpackWARN2(x) (((x) >>8) & 0xFF)
393 #define unpackWARN3(x) (((x) >>16) & 0xFF)
394 #define unpackWARN4(x) (((x) >>24) & 0xFF)
397 ( ! specialWARN(PL_curcop->cop_warnings) && \
398 ( isWARNf_on(PL_curcop->cop_warnings, WARN_ALL) || \
399 isWARNf_on(PL_curcop->cop_warnings, unpackWARN1(x)) || \
400 isWARNf_on(PL_curcop->cop_warnings, unpackWARN2(x)) || \
401 isWARNf_on(PL_curcop->cop_warnings, unpackWARN3(x)) || \
402 isWARNf_on(PL_curcop->cop_warnings, unpackWARN4(x))))
404 /* end of file warnings.h */
407 read_only_bottom_close_and_rename($warn);
411 last if /^KEYWORDS$/ ;
412 if ($_ eq "=for warnings.pl tree-goes-here\n") {
413 print $pm warningsTree($tree, " ");
420 print $pm "our %Offsets = (\n" ;
421 foreach my $k (sort { $a <=> $b } keys %ValueToName) {
422 my ($name, $version) = @{ $ValueToName{$k} };
425 if ( $last_ver != $version ) {
427 print $pm tab(4, " # Warnings Categories added in Perl $version");
430 print $pm tab(4, " '$name'"), "=> $k,\n" ;
431 $last_ver = $version;
434 print $pm " );\n\n" ;
436 print $pm "our %Bits = (\n" ;
437 foreach my $k (sort keys %list) {
440 my @list = sort { $a <=> $b } @$v ;
442 print $pm tab(4, " '$k'"), '=> "',
443 mkHex($warn_size, map $_ * 2 , @list),
444 '", # [', mkRange(@list), "]\n" ;
447 print $pm " );\n\n" ;
449 print $pm "our %DeadBits = (\n" ;
450 foreach my $k (sort keys %list) {
453 my @list = sort { $a <=> $b } @$v ;
455 print $pm tab(4, " '$k'"), '=> "',
456 mkHex($warn_size, map $_ * 2 + 1 , @list),
457 '", # [', mkRange(@list), "]\n" ;
460 print $pm " );\n\n" ;
461 print $pm '$NONE = "', ('\0' x $warn_size) , "\";\n" ;
462 print $pm '$DEFAULT = "', mkHex($warn_size, map $_ * 2, @def),
463 '", # [', mkRange(@def), "]\n" ;
464 print $pm '$LAST_BIT = ' . "$index ;\n" ;
465 print $pm '$BYTES = ' . "$warn_size ;\n" ;
470 read_only_bottom_close_and_rename($pm);
475 our $VERSION = '1.24';
477 # Verify that we're called correctly so that warnings will work.
478 # see also strict.pm.
479 unless ( __FILE__ =~ /(^|[\/\\])\Q${\__PACKAGE__}\E\.pmc?$/ ) {
480 my (undef, $f, $l) = caller;
481 die("Incorrect use of pragma '${\__PACKAGE__}' at $f line $l.\n");
486 warnings - Perl pragma to control optional warnings
496 use warnings::register;
497 if (warnings::enabled()) {
498 warnings::warn("some warning");
501 if (warnings::enabled("void")) {
502 warnings::warn("void", "some warning");
505 if (warnings::enabled($object)) {
506 warnings::warn($object, "some warning");
509 warnings::warnif("some warning");
510 warnings::warnif("void", "some warning");
511 warnings::warnif($object, "some warning");
515 The C<warnings> pragma gives control over which warnings are enabled in
516 which parts of a Perl program. It's a more flexible alternative for
517 both the command line flag B<-w> and the equivalent Perl variable,
520 This pragma works just like the C<strict> pragma.
521 This means that the scope of the warning pragma is limited to the
522 enclosing block. It also means that the pragma setting will not
523 leak across files (via C<use>, C<require> or C<do>). This allows
524 authors to independently define the degree of warning checks that will
525 be applied to their module.
527 By default, optional warnings are disabled, so any legacy code that
528 doesn't attempt to control the warnings will work unchanged.
530 All warnings are enabled in a block by either of these:
535 Similarly all warnings are disabled in a block by either of these:
540 For example, consider the code below:
550 The code in the enclosing block has warnings enabled, but the inner
551 block has them disabled. In this case that means the assignment to the
552 scalar C<$c> will trip the C<"Scalar value @a[0] better written as $a[0]">
553 warning, but the assignment to the scalar C<$b> will not.
555 =head2 Default Warnings and Optional Warnings
557 Before the introduction of lexical warnings, Perl had two classes of
558 warnings: mandatory and optional.
560 As its name suggests, if your code tripped a mandatory warning, you
561 would get a warning whether you wanted it or not.
562 For example, the code below would always produce an C<"isn't numeric">
563 warning about the "2:".
567 With the introduction of lexical warnings, mandatory warnings now become
568 I<default> warnings. The difference is that although the previously
569 mandatory warnings are still enabled by default, they can then be
570 subsequently enabled or disabled with the lexical warning pragma. For
571 example, in the code below, an C<"isn't numeric"> warning will only
572 be reported for the C<$a> variable.
578 Note that neither the B<-w> flag or the C<$^W> can be used to
579 disable/enable default warnings. They are still mandatory in this case.
581 =head2 What's wrong with B<-w> and C<$^W>
583 Although very useful, the big problem with using B<-w> on the command
584 line to enable warnings is that it is all or nothing. Take the typical
585 scenario when you are writing a Perl program. Parts of the code you
586 will write yourself, but it's very likely that you will make use of
587 pre-written Perl modules. If you use the B<-w> flag in this case, you
588 end up enabling warnings in pieces of code that you haven't written.
590 Similarly, using C<$^W> to either disable or enable blocks of code is
591 fundamentally flawed. For a start, say you want to disable warnings in
592 a block of code. You might expect this to be enough to do the trick:
600 When this code is run with the B<-w> flag, a warning will be produced
601 for the C<$a> line: C<"Reversed += operator">.
603 The problem is that Perl has both compile-time and run-time warnings. To
604 disable compile-time warnings you need to rewrite the code like this:
612 The other big problem with C<$^W> is the way you can inadvertently
613 change the warning setting in unexpected places in your code. For example,
614 when the code below is run (without the B<-w> flag), the second call
615 to C<doit> will trip a C<"Use of uninitialized value"> warning, whereas
630 This is a side-effect of C<$^W> being dynamically scoped.
632 Lexical warnings get around these limitations by allowing finer control
633 over where warnings can or can't be tripped.
635 =head2 Controlling Warnings from the Command Line
637 There are three Command Line flags that can be used to control when
638 warnings are (or aren't) produced:
645 This is the existing flag. If the lexical warnings pragma is B<not>
646 used in any of you code, or any of the modules that you use, this flag
647 will enable warnings everywhere. See L<Backward Compatibility> for
648 details of how this flag interacts with lexical warnings.
653 If the B<-W> flag is used on the command line, it will enable all warnings
654 throughout the program regardless of whether warnings were disabled
655 locally using C<no warnings> or C<$^W =0>.
656 This includes all files that get
657 included via C<use>, C<require> or C<do>.
658 Think of it as the Perl equivalent of the "lint" command.
663 Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.
667 =head2 Backward Compatibility
669 If you are used to working with a version of Perl prior to the
670 introduction of lexically scoped warnings, or have code that uses both
671 lexical warnings and C<$^W>, this section will describe how they interact.
673 How Lexical Warnings interact with B<-w>/C<$^W>:
679 If none of the three command line flags (B<-w>, B<-W> or B<-X>) that
680 control warnings is used and neither C<$^W> nor the C<warnings> pragma
681 are used, then default warnings will be enabled and optional warnings
683 This means that legacy code that doesn't attempt to control the warnings
688 The B<-w> flag just sets the global C<$^W> variable as in 5.005. This
689 means that any legacy code that currently relies on manipulating C<$^W>
690 to control warning behavior will still work as is.
694 Apart from now being a boolean, the C<$^W> variable operates in exactly
695 the same horrible uncontrolled global way, except that it cannot
696 disable/enable default warnings.
700 If a piece of code is under the control of the C<warnings> pragma,
701 both the C<$^W> variable and the B<-w> flag will be ignored for the
702 scope of the lexical warning.
706 The only way to override a lexical warnings setting is with the B<-W>
707 or B<-X> command line flags.
711 The combined effect of 3 & 4 is that it will allow code which uses
712 the C<warnings> pragma to control the warning behavior of $^W-type
713 code (using a C<local $^W=0>) if it really wants to, but not vice-versa.
715 =head2 Category Hierarchy
716 X<warning, categories>
718 A hierarchy of "categories" have been defined to allow groups of warnings
719 to be enabled/disabled in isolation.
721 The current hierarchy is:
723 =for warnings.pl tree-goes-here
725 Just like the "strict" pragma any of these categories can be combined
727 use warnings qw(void redefine);
728 no warnings qw(io syntax untie);
730 Also like the "strict" pragma, if there is more than one instance of the
731 C<warnings> pragma in a given scope the cumulative effect is additive.
733 use warnings qw(void); # only "void" warnings enabled
735 use warnings qw(io); # only "void" & "io" warnings enabled
737 no warnings qw(void); # only "io" warnings enabled
739 To determine which category a specific warning has been assigned to see
742 Note: Before Perl 5.8.0, the lexical warnings category "deprecated" was a
743 sub-category of the "syntax" category. It is now a top-level category
746 =head2 Fatal Warnings
749 The presence of the word "FATAL" in the category list will escalate any
750 warnings detected from the categories specified in the lexical scope
751 into fatal errors. In the code below, the use of C<time>, C<length>
752 and C<join> can all produce a C<"Useless use of xxx in void context">
760 use warnings FATAL => qw(void);
768 When run it produces this output
770 Useless use of time in void context at fatal line 3.
771 Useless use of length in void context at fatal line 7.
773 The scope where C<length> is used has escalated the C<void> warnings
774 category into a fatal error, so the program terminates immediately when it
775 encounters the warning.
777 To explicitly turn off a "FATAL" warning you just disable the warning
778 it is associated with. So, for example, to disable the "void" warning
779 in the example above, either of these will do the trick:
781 no warnings qw(void);
782 no warnings FATAL => qw(void);
784 If you want to downgrade a warning that has been escalated into a fatal
785 error back to a normal warning, you can use the "NONFATAL" keyword. For
786 example, the code below will promote all warnings into fatal errors,
787 except for those in the "syntax" category.
789 use warnings FATAL => 'all', NONFATAL => 'syntax';
791 As of Perl 5.20, instead of C<< use warnings FATAL => 'all'; >> you can
794 use v5.20; # Perl 5.20 or greater is required for the following
795 use warnings 'FATAL'; # short form of "use warnings FATAL => 'all';"
797 If you want your program to be compatible with versions of Perl before
798 5.20, you must use C<< use warnings FATAL => 'all'; >> instead. (In
799 previous versions of Perl, the behavior of the statements
800 C<< use warnings 'FATAL'; >>, C<< use warnings 'NONFATAL'; >> and
801 C<< no warnings 'FATAL'; >> was unspecified; they did not behave as if
802 they included the C<< => 'all' >> portion. As of 5.20, they do.)
804 B<NOTE:> Users of FATAL warnings, especially
805 those using C<< FATAL => 'all' >>
806 should be fully aware that they are risking future portability of their
807 programs by doing so. Perl makes absolutely no commitments to not
808 introduce new warnings, or warnings categories in the future, and indeed
809 we explicitly reserve the right to do so. Code that may not warn now may
810 warn in a future release of Perl if the Perl5 development team deems it
811 in the best interests of the community to do so. Should code using FATAL
812 warnings break due to the introduction of a new warning we will NOT
813 consider it an incompatible change. Users of FATAL warnings should take
814 special caution during upgrades to check to see if their code triggers
815 any new warnings and should pay particular attention to the fine print of
816 the documentation of the features they use to ensure they do not exploit
817 features that are documented as risky, deprecated, or unspecified, or where
818 the documentation says "so don't do that", or anything with the same sense
819 and spirit. Use of such features in combination with FATAL warnings is
820 ENTIRELY AT THE USER'S RISK.
822 =head2 Reporting Warnings from a Module
823 X<warning, reporting> X<warning, registering>
825 The C<warnings> pragma provides a number of functions that are useful for
826 module authors. These are used when you want to report a module-specific
827 warning to a calling module has enabled warnings via the C<warnings>
830 Consider the module C<MyMod::Abc> below.
834 use warnings::register;
838 if ($path !~ m#^/#) {
839 warnings::warn("changing relative path to /var/abc")
840 if warnings::enabled();
841 $path = "/var/abc/$path";
847 The call to C<warnings::register> will create a new warnings category
848 called "MyMod::Abc", i.e. the new category name matches the current
849 package name. The C<open> function in the module will display a warning
850 message if it gets given a relative path as a parameter. This warnings
851 will only be displayed if the code that uses C<MyMod::Abc> has actually
852 enabled them with the C<warnings> pragma like below.
855 use warnings 'MyMod::Abc';
857 abc::open("../fred.txt");
859 It is also possible to test whether the pre-defined warnings categories are
860 set in the calling module with the C<warnings::enabled> function. Consider
861 this snippet of code:
866 warnings::warnif("deprecated",
867 "open is deprecated, use new instead");
875 The function C<open> has been deprecated, so code has been included to
876 display a warning message whenever the calling module has (at least) the
877 "deprecated" warnings category enabled. Something like this, say.
879 use warnings 'deprecated';
882 MyMod::Abc::open($filename);
884 Either the C<warnings::warn> or C<warnings::warnif> function should be
885 used to actually display the warnings message. This is because they can
886 make use of the feature that allows warnings to be escalated into fatal
887 errors. So in this case
890 use warnings FATAL => 'MyMod::Abc';
892 MyMod::Abc::open('../fred.txt');
894 the C<warnings::warnif> function will detect this and die after
895 displaying the warning message.
897 The three warnings functions, C<warnings::warn>, C<warnings::warnif>
898 and C<warnings::enabled> can optionally take an object reference in place
899 of a category name. In this case the functions will use the class name
900 of the object as the warnings category.
902 Consider this example:
907 use warnings::register;
920 if ($value % 2 && warnings::enabled($self))
921 { warnings::warn($self, "Odd numbers are unsafe") }
928 $self->check($value);
936 use warnings::register;
938 our @ISA = qw( Original );
948 The code below makes use of both modules, but it only enables warnings from
953 use warnings 'Derived';
954 my $a = Original->new();
956 my $b = Derived->new();
959 When this code is run only the C<Derived> object, C<$b>, will generate
962 Odd numbers are unsafe at main.pl line 7
964 Notice also that the warning is reported at the line where the object is first
967 When registering new categories of warning, you can supply more names to
968 warnings::register like this:
971 use warnings::register qw(format precision);
975 warnings::warnif('MyModule::format', '...');
981 =item use warnings::register
983 Creates a new warnings category with the same name as the package where
984 the call to the pragma is used.
986 =item warnings::enabled()
988 Use the warnings category with the same name as the current package.
990 Return TRUE if that warnings category is enabled in the calling module.
991 Otherwise returns FALSE.
993 =item warnings::enabled($category)
995 Return TRUE if the warnings category, C<$category>, is enabled in the
997 Otherwise returns FALSE.
999 =item warnings::enabled($object)
1001 Use the name of the class for the object reference, C<$object>, as the
1004 Return TRUE if that warnings category is enabled in the first scope
1005 where the object is used.
1006 Otherwise returns FALSE.
1008 =item warnings::fatal_enabled()
1010 Return TRUE if the warnings category with the same name as the current
1011 package has been set to FATAL in the calling module.
1012 Otherwise returns FALSE.
1014 =item warnings::fatal_enabled($category)
1016 Return TRUE if the warnings category C<$category> has been set to FATAL in
1018 Otherwise returns FALSE.
1020 =item warnings::fatal_enabled($object)
1022 Use the name of the class for the object reference, C<$object>, as the
1025 Return TRUE if that warnings category has been set to FATAL in the first
1026 scope where the object is used.
1027 Otherwise returns FALSE.
1029 =item warnings::warn($message)
1031 Print C<$message> to STDERR.
1033 Use the warnings category with the same name as the current package.
1035 If that warnings category has been set to "FATAL" in the calling module
1036 then die. Otherwise return.
1038 =item warnings::warn($category, $message)
1040 Print C<$message> to STDERR.
1042 If the warnings category, C<$category>, has been set to "FATAL" in the
1043 calling module then die. Otherwise return.
1045 =item warnings::warn($object, $message)
1047 Print C<$message> to STDERR.
1049 Use the name of the class for the object reference, C<$object>, as the
1052 If that warnings category has been set to "FATAL" in the scope where C<$object>
1053 is first used then die. Otherwise return.
1056 =item warnings::warnif($message)
1060 if (warnings::enabled())
1061 { warnings::warn($message) }
1063 =item warnings::warnif($category, $message)
1067 if (warnings::enabled($category))
1068 { warnings::warn($category, $message) }
1070 =item warnings::warnif($object, $message)
1074 if (warnings::enabled($object))
1075 { warnings::warn($object, $message) }
1077 =item warnings::register_categories(@names)
1079 This registers warning categories for the given names and is primarily for
1080 use by the warnings::register pragma.
1084 See also L<perlmodlib/Pragmatic Modules> and L<perldiag>.
1090 $All = "" ; vec($All, $Offsets{'all'}, 2) = 3 ;
1094 require Carp; # this initializes %CarpInternal
1095 local $Carp::CarpInternal{'warnings'};
1096 delete $Carp::CarpInternal{'warnings'};
1106 foreach my $word ( @_ ) {
1107 if ($word eq 'FATAL') {
1111 elsif ($word eq 'NONFATAL') {
1115 elsif ($catmask = $Bits{$word}) {
1117 $mask |= $DeadBits{$word} if $fatal ;
1118 $mask &= ~($DeadBits{$word}|$All) if $no_fatal ;
1121 { Croaker("Unknown warnings category '$word'")}
1129 # called from B::Deparse.pm
1130 push @_, 'all' unless @_ ;
1131 return _bits(undef, @_) ;
1138 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
1140 if (vec($mask, $Offsets{'all'}, 1)) {
1141 $mask |= $Bits{'all'} ;
1142 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
1145 # append 'all' when implied (after a lone "FATAL" or "NONFATAL")
1146 push @_, 'all' if @_==1 && ( $_[0] eq 'FATAL' || $_[0] eq 'NONFATAL' );
1148 # Empty @_ is equivalent to @_ = 'all' ;
1149 ${^WARNING_BITS} = @_ ? _bits($mask, @_) : $mask | $Bits{all} ;
1157 my $mask = ${^WARNING_BITS} // ($^W ? $Bits{all} : $DEFAULT) ;
1159 if (vec($mask, $Offsets{'all'}, 1)) {
1160 $mask |= $Bits{'all'} ;
1161 $mask |= $DeadBits{'all'} if vec($mask, $Offsets{'all'}+1, 1);
1164 # append 'all' when implied (empty import list or after a lone "FATAL")
1165 push @_, 'all' if !@_ || @_==1 && $_[0] eq 'FATAL';
1167 foreach my $word ( @_ ) {
1168 if ($word eq 'FATAL') {
1171 elsif ($catmask = $Bits{$word}) {
1172 $mask &= ~($catmask | $DeadBits{$word} | $All);
1175 { Croaker("Unknown warnings category '$word'")}
1178 ${^WARNING_BITS} = $mask ;
1181 my %builtin_type; @builtin_type{qw(SCALAR ARRAY HASH CODE REF GLOB LVALUE Regexp)} = ();
1183 sub MESSAGE () { 4 };
1185 sub NORMAL () { 1 };
1193 my $has_message = $wanted & MESSAGE;
1195 unless (@_ == 1 || @_ == ($has_message ? 2 : 0)) {
1196 my $sub = (caller 1)[3];
1197 my $syntax = $has_message ? "[category,] 'message'" : '[category]';
1198 Croaker("Usage: $sub($syntax)");
1201 my $message = pop if $has_message;
1204 # check the category supplied.
1206 if (my $type = ref $category) {
1207 Croaker("not an object")
1208 if exists $builtin_type{$type};
1212 $offset = $Offsets{$category};
1213 Croaker("Unknown warnings category '$category'")
1214 unless defined $offset;
1217 $category = (caller(1))[0] ;
1218 $offset = $Offsets{$category};
1219 Croaker("package '$category' not registered for warnings")
1220 unless defined $offset ;
1228 while (do { { package DB; $pkg = (caller($i++))[0] } } ) {
1229 last unless @DB::args && $DB::args[0] =~ /^$category=/ ;
1234 $i = _error_loc(); # see where Carp will allocate the error
1237 # Default to 0 if caller returns nothing. Default to $DEFAULT if it
1238 # explicitly returns undef.
1239 my(@callers_bitmask) = (caller($i))[9] ;
1240 my $callers_bitmask =
1241 @callers_bitmask ? $callers_bitmask[0] // $DEFAULT : 0 ;
1244 foreach my $type (FATAL, NORMAL) {
1245 next unless $wanted & $type;
1247 push @results, (vec($callers_bitmask, $offset + $type - 1, 1) ||
1248 vec($callers_bitmask, $Offsets{'all'} + $type - 1, 1));
1251 # &enabled and &fatal_enabled
1252 return $results[0] unless $has_message;
1254 # &warnif, and the category is neither enabled as warning nor as fatal
1255 return if $wanted == (NORMAL | FATAL | MESSAGE)
1256 && !($results[0] || $results[1]);
1259 Carp::croak($message) if $results[0];
1260 # will always get here for &warn. will only get here for &warnif if the
1261 # category is enabled
1262 Carp::carp($message);
1270 vec($mask, $bit, 1) = 1;
1274 sub register_categories
1278 for my $name (@names) {
1279 if (! defined $Bits{$name}) {
1280 $Bits{$name} = _mkMask($LAST_BIT);
1281 vec($Bits{'all'}, $LAST_BIT, 1) = 1;
1282 $Offsets{$name} = $LAST_BIT ++;
1283 foreach my $k (keys %Bits) {
1284 vec($Bits{$k}, $LAST_BIT, 1) = 0;
1286 $DeadBits{$name} = _mkMask($LAST_BIT);
1287 vec($DeadBits{'all'}, $LAST_BIT++, 1) = 1;
1294 goto &Carp::short_error_loc; # don't introduce another stack frame
1299 return __chk(NORMAL, @_);
1304 return __chk(FATAL, @_);
1309 return __chk(FATAL | MESSAGE, @_);
1314 return __chk(NORMAL | FATAL | MESSAGE, @_);
1317 # These are not part of any public interface, so we can delete them to save
1319 delete @warnings::{qw(NORMAL FATAL MESSAGE)};