在MooseX :: Declare中创建BUILD方法的正确方法是什么?

时间:2009-07-20 20:34:34

标签: perl moose

我在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;

一切都运行得很好(但是其余的代码很丑陋而且不合适。)

3 个答案:

答案 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魔力。