在我的真实代码中,我希望"同步"一个Moo(或Moose,如果Moo赢了工作)对象有一个哈希(实际上是一个绑定的哈希),所以读取Moo对象的属性将从哈希读取相应的值并写入Moo的属性对象将存储到哈希值中。
以下是简化代码:
#!/usr/bin/perl
use feature qw(say);
package X;
use Moo;
use Data::Dumper;
my $BusinessClass = 'X';
has 'base' => (is => 'rw', builder => 'base_builder');
sub base_builder {
return {};
}
foreach my $Key (qw(a b c)) {
{
no strict 'refs';
*{"${BusinessClass}::$Key"} = sub {
if (@_ == 2) {
return $_[0]->base->{$Key} = $_[1];
} else {
return $_[0]->base->{$Key};
}
};
has $Key => ( is => 'rw',
lazy => 0,
required => 0,
reader => "${BusinessClass}::_access1_$Key",
writer => "${BusinessClass}::_access2_$Key",
);
}
}
my $obj = X->new(a=>123, b=>456);
print Dumper $obj->base;
$obj->c(789);
print Dumper $obj->base;
问题是传递给new
函数的属性没有存储在has $obj->base
中(但它们应该是)。在上面的代码示例中,属性c
已正确存储,但a
和b
未存储在哈希中。这是一个错误。
处理这种情况的好方法是什么?
答案 0 :(得分:2)
这可以通过添加:
来解决sub BUILD {
my ($self, $args) = @_;
foreach my $Key (keys %$args) {
$self->base->{$Key} = $args->{$Key};
my $clearer = "_clear_local_$Key";
$self->$clearer();
}
}
完整代码:
#!/usr/bin/perl
use feature qw(say);
package X;
use Moo;
use Data::Dumper;
my $BusinessClass = 'X';
has 'base' => (is => 'rw', builder => 'base_builder');
sub base_builder {
return {};
}
sub BUILD {
my ($self, $args) = @_;
foreach my $Key (keys %$args) {
$self->base->{$Key} = $args->{$Key};
my $clearer = "_clear_local_$Key";
$self->$clearer();
}
}
foreach my $Key (qw(a b c)) {
{
no strict 'refs';
*{"${BusinessClass}::$Key"} = sub {
if (@_ == 2) {
return $_[0]->base->{$Key} = $_[1];
} else {
return $_[0]->base->{$Key};
}
};
has $Key => ( is => 'rw',
lazy => 0,
required => 0,
reader => "${BusinessClass}::_access1_$Key",
writer => "${BusinessClass}::_access2_$Key",
clearer => "_clear_local_$Key",
);
}
}
my $obj = X->new(a=>123, b=>456);
print Dumper $obj->base;
$obj->c(789);
print Dumper $obj->base;
print Dumper {%$obj};