驼鹿& isa 数组引用
我正在尝试将 Moose 与 Moose::Meta::Attribute::Native::Trait::Array 一起使用,但看起来 ArrayRef 助手对我不起作用。下面是我的代码,它返回
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;
I am trying to use Moose with Moose::Meta::Attribute::Native::Trait::Array but it looks like ArrayRef helper doesn't work for me. Bellow is my code which returns
Can't call method "add_item" on unblessed reference at bug.pl line 42.
I use Moose 2.0007 and Perl v5.10.1. Moose::Autobox is installed.
I would appreciate any suggestion.
#!/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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
handles
将方法添加到类本身,而不是属性。另一个问题是splits
属性仍然是 arrayref,因此您需要在几秒钟内取消引用foreach
。更正后的代码如下:handles
add method to class itself, not to the attribute. Another problem is thatsplits
attribute is still arrayref, so you need dereference in secondsforeach
. Corrected code is as follows: