我正在开发一个简单的Perl模块,用于创建和验证音符,并找到等价的音符。我将一个包含所有有效注释的数组引用存储在一个模块中,然后将其导出,以便Note.pm
模块可以查看哪些注释是有效的,并在创建Note
对象时对照列表进行检查。
问题是,无论我尝试什么,导出的$VALID_NOTES
数组引用在Note.pm
中都不可见!我已经阅读了大约一千次关于Exporter
的文档,并回顾了大量使用Exporter
的旧Perl模块,我只是不知道这里出了什么问题。。。
这是代码:
test.pl
use strict;
use warnings;
use Music;
my $m = Music->new();
my $note = $m->note('C');
print $note;
音乐下午
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.
在Music.pm
中,在加载Note
:之前,在BEGIN块中填充@EXPORT_OK
package Music;
use Moose;
our @EXPORT_OK;
BEGIN { @EXPORT_OK = qw($VALID_NOTES) }
use Exporter qw(import);
use Note;