在别名子例程时收到"... used only once: possible typo"警告



我有一些模块,想为一些sub创建别名。下面是代码:

#!/usr/bin/perl
package MySub;
use strict;
use warnings;
sub new {
    my $class = shift;
    my $params = shift;
    my $self = {};
    bless( $self, $class );
    return $self;
}
sub do_some {
    my $self = shift;
    print "Do something!";
    return 1;
}
*other = &do_some;
1;

它工作,但它会产生一个编译警告

名称"MySub::other"只使用过一次:/tmp/MySub.pm第23行可能存在拼写错误。

我知道我可以只键入no warnings 'once';,但这是唯一的解决方案吗?Perl为什么警告我?我做错了什么?

{
   no warnings 'once';
   *other = &do_some;
}

*other = &do_some;
*other if 0;  # Prevent spurious warning

我更喜欢后者。对于初学者来说,它只会禁用您希望禁用的警告实例。此外,如果删除其中一行而忘记删除另一行,则另一行将开始发出警告。完美的

您应该再键入一点:

{   no warnings 'once';
    *other = &do_some;
}

通过这种方式,no warnings的影响仅被减少到有问题的线。

在Perl的较新版本中,no warnings杂注不足以阻止警告。相反,必须写下:

BEGIN {
  *bar = &foo;
}

(是的,不需要no warnings。)

相对于foo定义的顺序无关紧要;后续的sub foo也将定义bar,或者在没有任何foo定义的情况下调用bar将报告Undefined subroutine &main::bar

保持简单,保持小。

如果看到这样的警告:

名称只使用过一次:可能是打字错误

然后再次提到varname,使用just"我们的";像这样:

our $someNiceName;
$someNiceName = "any XYZ etc pp";

如果您的脚本引用并包含其他脚本:

require "otherScriptWithVarsAndDefinitions.cgi";

然后,var声明通常在每个脚本中只有一次。添加类似的行

our $someNiceName;

这将删除警告并解决问题。

相关内容

最新更新