抱歉有点长的代码,但想提供一个近乎有效的例子。
package MLQ::Jobs::Job {
use 5.016;
use Moose;
use warnings;
has 'name' => (is=>'rw', isa=>'Str');
has 'status' => (is=>'rw', isa=>'Str');
}
package MLQ::Jobs {
use 5.016;
use Moose;
use warnings;
#use MLQ::Jobs::Job;
has jobs => (
is => 'rw',
isa =>'ArrayRef[MLQ::Jobs::Job]', #jobs - an array of zero to many jobs
builder => '_scan_jobs', #initializing it when creating the object Jobs
);
sub _scan_jobs {
my $self = shift;
#test code
foreach my $i (1..10) {
my $j = MLQ::Jobs::Job->new();
$j->name("name $i");
$j->status("stat $i");
push @{$self->{jobs}}, $j;
}
}
}
package main {
use 5.016;
use warnings;
use Data::Dumper;
#use MLQ::Jobs;
my $j = MLQ::Jobs->new();
say Dumper $j;
}
运行上述代码时,得到10行长的错误消息什么是不有帮助。至少对一个偶然的perl程序员没有帮助 - 就像我...... :(理解第一行,但在代码中找不到错误...
Attribute (jobs) does not pass the type constraint because: Validation failed for 'ArrayRef[MLQ::Jobs::Job]' with value at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1289.
Moose::Meta::Attribute::verify_against_type_constraint('Moose::Meta::Attribute=HASH(0x7fce1082ec78)', '', 'instance', 'MLQ::Jobs=HASH(0x7fce1082a378)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 1276
Moose::Meta::Attribute::_coerce_and_verify('Moose::Meta::Attribute=HASH(0x7fce1082ec78)', '', 'MLQ::Jobs=HASH(0x7fce1082a378)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Attribute.pm line 546
Moose::Meta::Attribute::initialize_instance_slot('Moose::Meta::Attribute=HASH(0x7fce1082ec78)', 'Moose::Meta::Instance=HASH(0x7fce1082f4a0)', 'MLQ::Jobs=HASH(0x7fce1082a378)', 'HASH(0x7fce1082a360)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 525
Class::MOP::Class::_construct_instance('Moose::Meta::Class=HASH(0x7fce108372a8)', 'HASH(0x7fce1082a360)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Class/MOP/Class.pm line 498
Class::MOP::Class::new_object('Moose::Meta::Class=HASH(0x7fce108372a8)', 'HASH(0x7fce1082a360)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Meta/Class.pm line 274
Moose::Meta::Class::new_object('Moose::Meta::Class=HASH(0x7fce108372a8)', 'HASH(0x7fce1082a360)') called at /Users/me/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level/Moose/Object.pm line 28
Moose::Object::new('MLQ::Jobs') called at moo2.pl line 38
答案 0 :(得分:5)
问题是builder
方法(如default
)应该返回要放在属性中的值,而不是初始化属性本身。你可以用BUILD
方法做到这一点。
sub _scan_jobs {
my $self = shift;
my @jobs;
foreach my $i (1..10) {
my $j = MLQ::Jobs::Job->new();
$j->name("name $i");
$j->status("stat $i");
push @jobs, $j;
}
return \@jobs;
}