2

我正在开发一个简单的 Perl 模块来创建和验证音符并找到等音的等价音符。我在模块中存储一个包含所有有效注释的数组引用,然后将其导出,以便Note.pm模块可以查看哪些注释是有效的,并在创建Note对象时检查列表。

问题是,无论我尝试什么,导出的$VALID_NOTES数组引用在Note.pm! 我已经阅读了Exporter大约一千遍的文档,并回顾了我使用的大量旧 Perl 模块,Exporter但我无法弄清楚这里出了什么问题......

这是代码:

测试.pl

use strict;
use warnings;
use Music;

my $m = Music->new();

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

print $note;

音乐.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;

注意.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.
4

1 回答 1

4

在中,在加载之前Music.pm填充@EXPORT_OKBEGIN 块:Note

package Music;
use Moose;
our @EXPORT_OK;
BEGIN { @EXPORT_OK = qw($VALID_NOTES) }
use Exporter qw(import);
use Note;
于 2017-10-13T15:13:02.357 回答