我有一些我正在处理的遗留代码.一次性清理太多了.它在s运算符内部使用\ 1.我查看了perllexwarn,发现我可以用'没有警告qw(语法)'来关闭它,但我通过反复试验做到了这一点.是否有更简单的方法从警告到关闭它的方式?
它正在做这样的事情:
use strict;
$_ = "abc";
s/abc/\1/;
no warnings qw(syntax);
s/abc/\1/;
Run Code Online (Sandbox Code Playgroud)
它生成的消息是:
\1 better written as $1
Run Code Online (Sandbox Code Playgroud)
我会创建一个全局信号处理程序,将其设置为一个BEGIN块,以便在早期编译,并且只跳过你不想要的警告,这样你仍然会得到任何潜在的意外和不相关的警告(即使在同一类别中,由于不必禁用整个事情):
use warnings;
use strict;
BEGIN {
$SIG{__WARN__} = sub {
my $warn = shift;
return if $warn =~ /\\\d better written as/;
warn $warn;
};
}
my $x = 'abc';
$x =~ s/(abc)/\1/;
warn "a different warning\n";
Run Code Online (Sandbox Code Playgroud)
输出:
a different warning
Run Code Online (Sandbox Code Playgroud)
执行你的脚本
perl -Mdiagnostics ./a.pl
Run Code Online (Sandbox Code Playgroud)
或暂时添加use diagnostics;到您的脚本.这将产生类似的东西
\1 better written as $1 at ./a.pl line 4 (#1)
(W syntax) Outside of patterns, backreferences live on as variables.
The use of backslashes is grandfathered on the right-hand side of a
substitution, but stylistically it's better to use the variable form
because other Perl programmers will expect it, and it works better if
there are more than 9 backreferences.
Run Code Online (Sandbox Code Playgroud)
请注意(W syntax)?这封信是以下之一,这个词就是您正在寻找的警告类.
诊断从perldiag获取其信息,您可以手动搜索而不是使用use diagnostics;.
其他例子:
$ perl -Mdiagnostics -we'print undef'
Use of uninitialized value in print at -e line 1 (#1)
(W uninitialized) An undefined value was used as if it were already
[...]
$ perl -Mdiagnostics -we'no warnings qw( uninitialized ); print undef'
$ perl -Mdiagnostics -we'sub foo { } sub foo { }'
Subroutine foo redefined at -e line 1 (#1)
(W redefine) You redefined a subroutine. To suppress this warning, say
[...]
$ perl -Mdiagnostics -we'no warnings qw( redefine ); sub foo { } sub foo { }'
$
Run Code Online (Sandbox Code Playgroud)