我正在尝试使用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;
答案 0 :(得分: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;
}