导出后导出的变量仍然不可见

时间:2017-10-13 14:56:28

标签: perl scope packages exporter

我正在研究一个简单的Perl模块,用于创建和验证音符以及查找非等效音符。我正在存储一个包含模块中所有有效注释的数组引用,然后将其导出,以便Note.pm模块可以查看哪些注释有效,并在创建Note对象时检查列表。< / p>

问题是,无论我尝试什么,导出的$VALID_NOTES数组引用在Note.pm中都不可见!我已经阅读了Exporter上的文档大约一千次,并回顾了大量使用Exporter的旧Perl模块,我无法弄清楚这里有什么问题...... < / p>

以下是代码:

test.pl

use strict;
use warnings;
use Music;

my $m = Music->new();

my $note = $m->note('C');

print $note;

Music.pm

package Music;

use Moose;
use Note;

use Exporter qw(import);
our @EXPORT_OK = qw($VALID_NOTES);

no warnings 'qw';

# Valid notes
# Enharmonic notes are in preferred (most common) order:
#     Natural -> Sharp -> Flat -> Double Sharp -> Double Flat
our $VALID_NOTES = [
    [ qw(C B#        Dbb) ],
    [ qw(  C# Db B##    ) ],
    [ qw(D       C## Ebb) ],
    [ qw(  D# Eb     Fbb) ],
    [ qw(E    Fb D##    ) ],
    [ qw(F E#        Gbb) ],
    [ qw(  F# Gb E##    ) ],
    [ qw(G       F## Abb) ],
    [ qw(  G# Ab        ) ],
    [ qw(A       G## Bbb) ],
    [ qw(  A# Bb     Cbb) ],
    [ qw(B    Cb A##    ) ],
];

sub note {
    my $self = shift;
    my $name = shift;
    return Note->new(name => $name);
}

__PACKAGE__->meta->make_immutable;

Note.pm

package Note;

use Moose;
use Music qw($VALID_NOTES);
use experimental 'smartmatch';

has 'name'  => (is => 'ro', isa => 'Str', required => 1);
has 'index' => (is => 'ro', isa => 'Int', lazy => 1, builder => '_get_index');

# Overload stringification
use overload fallback => 1, '""' => sub { shift->name() };

sub BUILD {
    my $self = shift;
    if (!grep { $self ~~ @{$VALID_NOTES->[$_]} } 0..$#{$VALID_NOTES}) {
        die "Invalid note: '$self'\n";
    }
}

sub _get_index {
    my $self = shift;
    my ($index) = grep { $self ~~ @{$VALID_NOTES->[$_]} } 0..$#{$VALID_NOTES};
    return $index;
}

sub enharmonic_notes {
    my $self = shift;
    my $index = $self->index();
    return map { Note->new($_) } @{$VALID_NOTES->[$index]};
}

__PACKAGE__->meta->make_immutable;

当我运行代码时,我得到了这个输出:

Global symbol "$VALID_NOTES" requires explicit package name at Note.pm line 15.
Global symbol "$VALID_NOTES" requires explicit package name at Note.pm line 15.
Global symbol "$VALID_NOTES" requires explicit package name at Note.pm line 22.
Global symbol "$VALID_NOTES" requires explicit package name at Note.pm line 22.
Global symbol "$VALID_NOTES" requires explicit package name at Note.pm line 29.

1 个答案:

答案 0 :(得分:4)

Music.pm中,在加载@EXPORT_OK之前填充BEGIN块中的Note

package Music;
use Moose;
our @EXPORT_OK;
BEGIN { @EXPORT_OK = qw($VALID_NOTES) }
use Exporter qw(import);
use Note;