我有代码有,
no warnings 'once';
阅读man warnings
我没有看到/once/
这有什么作用?
只要你没有打开strict
,perl 允许你使用变量而不声明它。
perl -wE'$foo = 4;'
哪些输出,
名称
main::foo
仅使用一次:第 1 行-e
可能有拼写错误。
请注意,strict
这甚至不允许
全局符号
$foo
需要在 -e 第 1 行处显式包名称(您是否忘记声明my $foo
?
不过,您可以禁用警告,而无需通过执行no warnings "once";
来启用strict
尽管我强烈建议您只需删除未使用的代码而不是使警告静音即可。
perl -wE'no warnings "once"; $foo = 4;'
这既看起来丑陋又什么也没做。
如果运行以下命令,将触发警告,并添加一些额外的说明:
perl -Mdiagnostics -Mwarnings -e '$foo=1'
输出将是:
Name "main::foo" used only once: possible typo at -e line 1 (#1)
(W once) Typographical errors often show up as unique variable names.
If you had a good reason for having a unique name, then just mention it
again somehow to suppress the message. The our declaration is
provided for this purpose.
NOTE: This warning detects symbols that have been used only once so $c, @c,
%c, *c, &c, sub c{}, c(), and c (the filehandle or format) are considered
the same; if a program uses $c only once but also uses any of the others it
该警告适用于符号表条目(不是"我的"词法变量)。 如果向上述内容添加-Mstrict
,则会创建严格违规,因为变量违反了strict 'vars'
,这禁止您使用尚未声明的变量,但由其完全限定名称引用的包全局变量除外。 如果要使用our
预先声明$foo
,则警告将消失:
perl -Mdiagnostics -Mwarnings -Mstrict=vars -E 'our $foo=1'
这工作得很好;它避免了严格的违规,并避免了"一次"警告。 因此,警告的目的是提醒您使用未声明的标识符,不使用完全限定的名称,并且只使用一次。 目的是帮助防止符号名称中的拼写错误,假设如果您只使用符号名称一次并且没有声明它,则可能是错误的。
特殊(标点符号)变量免于此检查。因此,您只能引用一次$_
或$/
,而不会触发警告。此外,$a
和$b
是免税的,因为它们被认为是特殊的,用于sort {$a <=> $b} @list
;在这样的结构中,它们可能只出现一次,但对相当典型的代码发出警告是没有用的。
您可以在此处找到警告层次结构中列出的"一次"警告:perldoc 警告。
所有诊断简介的列表可在perldoc perldiag中找到。