📄 perllexwarn.pod
字号:
=head1 NAMEperllexwarn - Perl Lexical Warnings=head1 DESCRIPTIONThe C<use warnings> pragma is a replacement for both the command lineflag B<-w> and the equivalent Perl variable, C<$^W>.The pragma works just like the existing "strict" pragma.This means that the scope of the warning pragma is limited to theenclosing block. It also means that the pragma setting will notleak across files (via C<use>, C<require> or C<do>). This allowsauthors to independently define the degree of warning checks that willbe applied to their module.By default, optional warnings are disabled, so any legacy code thatdoesn't attempt to control the warnings will work unchanged.All warnings are enabled in a block by either of these: use warnings ; use warnings 'all' ;Similarly all warnings are disabled in a block by either of these: no warnings ; no warnings 'all' ;For example, consider the code below: use warnings ; my @a ; { no warnings ; my $b = @a[0] ; } my $c = @a[0];The code in the enclosing block has warnings enabled, but the innerblock has them disabled. In this case that means the assignment to thescalar C<$c> will trip the C<"Scalar value @a[0] better written as $a[0]">warning, but the assignment to the scalar C<$b> will not.=head2 Default Warnings and Optional WarningsBefore the introduction of lexical warnings, Perl had two classes ofwarnings: mandatory and optional. As its name suggests, if your code tripped a mandatory warning, youwould get a warning whether you wanted it or not.For example, the code below would always produce an C<"isn't numeric">warning about the "2:". my $a = "2:" + 3;With the introduction of lexical warnings, mandatory warnings now becomeI<default> warnings. The difference is that although the previouslymandatory warnings are still enabled by default, they can then besubsequently enabled or disabled with the lexical warning pragma. Forexample, in the code below, an C<"isn't numeric"> warning will onlybe reported for the C<$a> variable. my $a = "2:" + 3; no warnings ; my $b = "2:" + 3;Note that neither the B<-w> flag or the C<$^W> can be used todisable/enable default warnings. They are still mandatory in this case.=head2 What's wrong with B<-w> and C<$^W>Although very useful, the big problem with using B<-w> on the commandline to enable warnings is that it is all or nothing. Take the typicalscenario when you are writing a Perl program. Parts of the code youwill write yourself, but it's very likely that you will make use ofpre-written Perl modules. If you use the B<-w> flag in this case, youend up enabling warnings in pieces of code that you haven't written.Similarly, using C<$^W> to either disable or enable blocks of code isfundamentally flawed. For a start, say you want to disable warnings ina block of code. You might expect this to be enough to do the trick: { local ($^W) = 0 ; my $a =+ 2 ; my $b ; chop $b ; }When this code is run with the B<-w> flag, a warning will be producedfor the C<$a> line -- C<"Reversed += operator">.The problem is that Perl has both compile-time and run-time warnings. Todisable compile-time warnings you need to rewrite the code like this: { BEGIN { $^W = 0 } my $a =+ 2 ; my $b ; chop $b ; }The other big problem with C<$^W> is the way you can inadvertentlychange the warning setting in unexpected places in your code. For example,when the code below is run (without the B<-w> flag), the second callto C<doit> will trip a C<"Use of uninitialized value"> warning, whereasthe first will not. sub doit { my $b ; chop $b ; } doit() ; { local ($^W) = 1 ; doit() }This is a side-effect of C<$^W> being dynamically scoped.Lexical warnings get around these limitations by allowing finer controlover where warnings can or can't be tripped.=head2 Controlling Warnings from the Command LineThere are three Command Line flags that can be used to control whenwarnings are (or aren't) produced:=over 5=item B<-w>This is the existing flag. If the lexical warnings pragma is B<not>used in any of you code, or any of the modules that you use, this flagwill enable warnings everywhere. See L<Backward Compatibility> fordetails of how this flag interacts with lexical warnings.=item B<-W>If the B<-W> flag is used on the command line, it will enable all warningsthroughout the program regardless of whether warnings were disabledlocally using C<no warnings> or C<$^W =0>. This includes all files that getincluded via C<use>, C<require> or C<do>.Think of it as the Perl equivalent of the "lint" command.=item B<-X>Does the exact opposite to the B<-W> flag, i.e. it disables all warnings.=back=head2 Backward CompatibilityIf you are used with working with a version of Perl prior to theintroduction of lexically scoped warnings, or have code that uses bothlexical warnings and C<$^W>, this section will describe how they interact.How Lexical Warnings interact with B<-w>/C<$^W>:=over 5=item 1.If none of the three command line flags (B<-w>, B<-W> or B<-X>) thatcontrol warnings is used and neither C<$^W> or the C<warnings> pragmaare used, then default warnings will be enabled and optional warningsdisabled.This means that legacy code that doesn't attempt to control the warningswill work unchanged.=item 2.The B<-w> flag just sets the global C<$^W> variable as in 5.005 -- thismeans that any legacy code that currently relies on manipulating C<$^W>to control warning behavior will still work as is. =item 3.Apart from now being a boolean, the C<$^W> variable operates in exactlythe same horrible uncontrolled global way, except that it cannotdisable/enable default warnings.=item 4.If a piece of code is under the control of the C<warnings> pragma,both the C<$^W> variable and the B<-w> flag will be ignored for thescope of the lexical warning.=item 5.The only way to override a lexical warnings setting is with the B<-W>or B<-X> command line flags.=backThe combined effect of 3 & 4 is that it will allow code which usesthe C<warnings> pragma to control the warning behavior of $^W-typecode (using a C<local $^W=0>) if it really wants to, but not vice-versa.=head2 Category HierarchyA hierarchy of "categories" have been defined to allow groups of warningsto be enabled/disabled in isolation.The current hierarchy is: all -+ | +- chmod | +- closure | +- exiting | +- glob | +- io -----------+ | | | +- closed | | | +- exec | | | +- newline | | | +- pipe | | | +- unopened | +- misc | +- numeric | +- once | +- overflow | +- pack | +- portable | +- recursion | +- redefine | +- regexp | +- severe -------+ | | | +- debugging | | | +- inplace | | | +- internal | | | +- malloc | +- signal | +- substr | +- syntax -------+ | | | +- ambiguous | | | +- bareword | | | +- deprecated | | | +- digit | | | +- parenthesis | | | +- precedence | | | +- printf | | | +- prototype | | | +- qw | | | +- reserved | | | +- semicolon | +- taint | +- umask | +- uninitialized | +- unpack | +- untie | +- utf8 | +- void | +- y2kJust like the "strict" pragma any of these categories can be combined use warnings qw(void redefine) ; no warnings qw(io syntax untie) ;Also like the "strict" pragma, if there is more than one instance of theC<warnings> pragma in a given scope the cumulative effect is additive. use warnings qw(void) ; # only "void" warnings enabled ... use warnings qw(io) ; # only "void" & "io" warnings enabled ... no warnings qw(void) ; # only "io" warnings enabledTo determine which category a specific warning has been assigned to seeL<perldiag>.=head2 Fatal WarningsThe presence of the word "FATAL" in the category list will escalate anywarnings detected from the categories specified in the lexical scopeinto fatal errors. In the code below, the use of C<time>, C<length>and C<join> can all produce a C<"Useless use of xxx in void context">warning. use warnings ; time ; { use warnings FATAL => qw(void) ; length "abc" ; } join "", 1,2,3 ; print "done\n" ; When run it produces this output Useless use of time in void context at fatal line 3. Useless use of length in void context at fatal line 7. The scope where C<length> is used has escalated the C<void> warningscategory into a fatal error, so the program terminates immediately itencounters the warning.=head2 Reporting Warnings from a ModuleThe C<warnings> pragma provides a number of functions that are useful formodule authors. These are used when you want to report a module-specificwarning to a calling module has enabled warnings via the C<warnings>pragma.Consider the module C<MyMod::Abc> below. package MyMod::Abc; use warnings::register; sub open { my $path = shift ; if (warnings::enabled() && $path !~ m#^/#) { warnings::warn("changing relative path to /tmp/"); $path = "/tmp/$path" ; } } 1 ;The call to C<warnings::register> will create a new warnings categorycalled "MyMod::abc", i.e. the new category name matches the currentpackage name. The C<open> function in the module will display a warningmessage if it gets given a relative path as a parameter. This warningswill only be displayed if the code that uses C<MyMod::Abc> has actuallyenabled them with the C<warnings> pragma like below. use MyMod::Abc; use warnings 'MyMod::Abc'; ... abc::open("../fred.txt");It is also possible to test whether the pre-defined warnings categories areset in the calling module with the C<warnings::enabled> function. Considerthis snippet of code: package MyMod::Abc; sub open { warnings::warnif("deprecated", "open is deprecated, use new instead") ; new(@_) ; } sub new ... 1 ;The function C<open> has been deprecated, so code has been included todisplay a warning message whenever the calling module has (at least) the"deprecated" warnings category enabled. Something like this, say. use warnings 'deprecated'; use MyMod::Abc; ... MyMod::Abc::open($filename) ;Either the C<warnings::warn> or C<warnings::warnif> function should beused to actually display the warnings message. This is because they canmake use of the feature that allows warnings to be escalated into fatalerrors. So in this case use MyMod::Abc; use warnings FATAL => 'MyMod::Abc'; ... MyMod::Abc::open('../fred.txt');the C<warnings::warnif> function will detect this and die afterdisplaying the warning message.The three warnings functions, C<warnings::warn>, C<warnings::warnif>and C<warnings::enabled> can optionally take an object reference in placeof a category name. In this case the functions will use the class nameof the object as the warnings category.Consider this example: package Original ; no warnings ; use warnings::register ; sub new { my $class = shift ; bless [], $class ; } sub check { my $self = shift ; my $value = shift ; if ($value % 2 && warnings::enabled($self)) { warnings::warn($self, "Odd numbers are unsafe") } } sub doit { my $self = shift ; my $value = shift ; $self->check($value) ; # ... } 1 ; package Derived ; use warnings::register ; use Original ; our @ISA = qw( Original ) ; sub new { my $class = shift ; bless [], $class ; } 1 ;The code below makes use of both modules, but it only enables warnings from C<Derived>. use Original ; use Derived ; use warnings 'Derived'; my $a = new Original ; $a->doit(1) ; my $b = new Derived ; $a->doit(1) ;When this code is run only the C<Derived> object, C<$b>, will generatea warning. Odd numbers are unsafe at main.pl line 7Notice also that the warning is reported at the line where the object is firstused.=head1 TODO perl5db.pl The debugger saves and restores C<$^W> at runtime. I haven't checked whether the debugger will still work with the lexical warnings patch applied. diagnostics.pm I *think* I've got diagnostics to work with the lexical warnings patch, but there were design decisions made in diagnostics to work around the limitations of C<$^W>. Now that those limitations are gone, the module should be revisited. document calling the warnings::* functions from XS=head1 SEE ALSOL<warnings>, L<perldiag>.=head1 AUTHORPaul Marquess
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -