不使用我们的 Perl 包变量

Perl package variables without using our

是否可以在不使用我们的情况下设置包变量

这是一个比文字更能解释案例的代码示例:

package A::B::C;

use strict;
use warnings;
use Exporter ();
our @ISA = qw/Exporter/;
our @EXPORT = ();
our @EXPORT_OK = qw/INFO/;
our %EXPORT_TAGS = (
    default => [qw/INFO/]
);
Exporter::export_ok_tags("default");

BEGIN {
    $C::verbose = 0;
}

sub INFO {
    my $msg = shift;

    if ($C::verbose) {
        print("$msg\n");
    }
}

从使用包 A::B::C 的脚本中设置变量 $verbose 不会更改包中 $verbose 的值:

use A::B::C;

$A::B::C::verbose = 1;

我完全知道在包中使用 'our' 可以解决问题,但我更想知道发生了什么以及为什么无法从使用包的脚本中设置变量 $verbose A::B::C。或者更好的是,只在包子例程中使用(而不是正式声明)的包变量会发生什么?他们得到什么范围?

您需要引用正确的包名称:$verbose 不在包 C 中,而是在 A::B::C 中。所以下面的工作按预期进行:

BEGIN {
    $A::B::C::verbose = 0; # Changed
}

sub INFO {
    my $msg = shift;

    if ($A::B::C::verbose) { # Changed
        print("$msg\n");
    }
}