我试图使用Moose与Moose :: Meta :: Attribute :: Native :: Trait :: Array但它看起来像ArrayRef helper对我不起作用.贝娄是我的代码返回
Can't call method "add_item" on unblessed reference at bug.pl line 42.
我使用Moose 2.0007和Perl v5.10.1.Moose :: Autobox已安装.我将不胜感激任何建议.
#!/usr/bin/perl
use strict;
package CycleSplit;
use Moose;
has 'name'=>(isa=>'Str', is=>'rw');
has 'start'=>(isa=>'Num', is=>'rw');
has 'length'=>(isa=>'Num', is=>'rw');
1;
package Cycle;
use Moose;
my @empty=();
has 'name' => (isa => 'Str', is => 'rw');
has 'splits' => (
traits => ['Array'],
isa=>'ArrayRef[CycleSplit]',
is => 'rw',
default=>sub { [] },
handles=>{
add_item=>'push',
},
);
no Moose;
1;
package Main;
sub Main {
my $cyc=Cycle->new();
$cyc->name("Days of week");
for my $i (1..7) {
my $spl=CycleSplit->new();
$spl->name("Day $i");
$spl->start($i/7-(1/7));
$spl->length(1/7);
$cyc->splits->add_item($spl);
}
my $text='';
foreach my $spl ($cyc->splits) {
$text.=$spl->name." ";
}
print $text;
}
Main;
bvr*_*bvr 11
handles将方法添加到类本身,而不是属性.另一个问题是splits属性仍然是arrayref,因此您需要在几秒钟内取消引用foreach.更正后的代码如下:
sub Main {
my $cyc=Cycle->new();
$cyc->name("Days of week");
for my $i (1..7) {
my $spl=CycleSplit->new();
$spl->name("Day $i");
$spl->start($i/7-(1/7));
$spl->length(1/7);
$cyc->add_item($spl); # removed splits
}
my $text='';
foreach my $spl (@{ $cyc->splits }) { # added array dereference
$text.=$spl->name." ";
}
print $text;
}
Run Code Online (Sandbox Code Playgroud)