我在MooseX::Declare中使用BUILD
方法时遇到了问题。如果我说:
#!/usr/bin/perl
use MooseX::Declare;
class Foo {
has foo => (is => "rw", isa => "Str", default => "foo");
method BUILD {
print "I was called\n";
}
}
Foo->new;
我收到以下不太有用的错误消息:
Reference found where even-sized list expected at /Users/cowens/perl5/lib/perl5/MooseX/Method/Signatures/Meta/Method.pm line 335.
Validation failed for 'MooseX::Types::Structured::Tuple[MooseX::Types::Structured::Tuple[Object],MooseX::Types::Structured::Dict[]]' failed with value [ [ Foo=HASH(0x804b20) ], { HASH(0x8049e0) => undef } ], Internal Validation Error is: Validation failed for 'MooseX::Types::Structured::Dict[]' failed with value { HASH(0x8049e0) => undef } at /Users/cowens/perl5/lib/perl5/MooseX/Method/Signatures/Meta/Method.pm line 365
MooseX::Method::Signatures::Meta::Method::validate('MooseX::Method::Signatures::Meta::Method=HASH(0xb8aab0)', 'ARRAY(0xb8ab30)') called at /Users/cowens/perl5/lib/perl5/MooseX/Method/Signatures/Meta/Method.pm line 139
Foo::BUILD('Foo=HASH(0x804b20)', 'HASH(0x8049e0)') called at generated method (unknown origin) line 25
Foo::new('Foo') called at test.pl line 13
但如果我说:
#!/usr/bin/perl
use MooseX::Declare;
class Foo {
has foo => (is => "rw", isa => "Str", default => "foo");
sub BUILD {
my $self = shift;
print "I was called\n";
}
}
Foo->new;
一切都运行得很好(但是其余的代码很丑陋而且不合适。)
答案 0 :(得分:6)
BUILD需要一个arg,只需说:
method BUILD($) { ... }
答案 1 :(得分:5)
它失败了因为BUILD
需要一个arg方法签名。默认情况下,MooseX::Declare
会创建一个与BUILD
调用方式不兼容的签名。 (细节对我来说很模糊。)我知道因为我遇到过类似的错误一次。我当然同意错误信息可能更具启发性;很多Moose的东西都是如此。
无论如何,我让它像这样工作:
use MooseX::Declare;
class Foo {
has foo => (is => "rw", isa => "Str", default => "foo");
method BUILD(Item $href) {
print "I was called\n";
}
}
Foo->new;
希望有所帮助。
您可以摆弄签名并尝试更具体的类型;我认为Moose发送了一个尚未完成的对象的hashref作为参数。
答案 2 :(得分:-2)
Perl理解sub
,因此可以输入当前包的符号表。 & Foo :: BUILD,在Devel::Declare之后,其他魔法从类闭包中创建了一个包范围。
Moose专门查找BUILD
子,以允许您操作构造函数逻辑。我的猜测(虽然我还没有完全追溯)是MooseX模块不会像Moose那样做。因此,本机BUILD
将永远传递给Moose魔法以确定构造函数逻辑。
另一方面,method
关键字在元类结构中创建方法更具有Devel::Declare魔力。