2
對不起,有點長的代碼,但要提供一個幾乎可行的例子。如何在駝鹿中使用ArrayRef [Class]
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
'推@。{$自我 - > {工作}}, $ j;'繞過你設置的'jobs'訪問器方法,並直接寫入數組ref,它應該是'push @ {$ self-> jobs},$ j'。因爲你使用的是5.16,所以你可以做'推$ self>工作,$ j'。 – Schwern