为什么Moo的构建器方法只能访问其他一些属性?

Pet*_*rch 2 perl moo

我期待一个构建器方法可以访问调用者提供的所有其他属性.但它似乎只能访问那些名字按字母顺序小于当前属性的人.例如,为什么b这里的建造者能看到价值a而不是c?('a'和'c'都出现在最终对象中)

码:

#!/usr/bin/perl -w
use strict;
use Data::Dumper;
{
    package P;
    use Moo;

    printf "Moo version: %s\n", $Moo::VERSION;

    # a and c are defined in the same way
    has a => ( is => 'ro' );
    has c => ( is => 'ro' );
    has b => (
        is => 'ro',
        builder => '_build_b',
    );

    sub _build_b {
        my ($self) = @_;
        print Data::Dumper->new(
            [ $self ], [ 'self_during_build_b' ]
        )->Indent(1)->Sortkeys(1)->Dump;
        return "somebuiltvalue";
    }
}
my $p = P->new({ a => 1, c => 3 });
print Data::Dumper->new([$p],['p'])->Indent(1)->Sortkeys(1)->Dump;
Run Code Online (Sandbox Code Playgroud)

输出:

Moo version: 2.003004
$self_during_build_b = bless( {
  'a' => 1
}, 'P' );
$p = bless( {
  'a' => 1,
  'b' => 'somebuiltvalue',
  'c' => 3
}, 'P' );
Run Code Online (Sandbox Code Playgroud)

Sin*_*nür 6

实际上,您不应该为构建器中的特定成员假设任何其他字段.如果类的某个成员的值取决于一个或多个其他成员的值,那么处理它的适当位置将是类BUILD方法.

我不确切地知道你想要实现什么,但你在寻找懒惰吗?

或者,也许b需要成为班上的一种方法