如何从其中一个属性生成的哈希构造moose对象?

时间:2012-01-29 09:29:08

标签: perl moose

我有几个套餐:

package FOO;
use Moose;
has 'obj' => (is=>'ro');
sub hash { 
    my $self = shift;
    return $self->make_hash($self->obj}; 
}

和另一个扩展FOO的包:

package FOOBAR;
use Moose;
extends 'FOO';
has [qw/val1 val2/] => (is => 'rw');
sub BUILD {
    my ($self) = @_;
    $self->val1($self->hash->{val1});
    $self->val2($self->hash->{val2});
}

基本上我想做FOOBAR->new(obj=>$obj);并使用从$obj生成的哈希来填充FOOBAR中指定的属性(~20左右属性)

正在使用' BUILD'这样一个很好的解决方法吗?

1 个答案:

答案 0 :(得分:1)

为什么呢?然后你最终得到两份数据。代替参加。

has obj => (
   is      => 'ro',
   handles => {
      val1 => sub { my $self = shift; my $obj = $self->obj; ... },
      val2 => sub { my $self = shift; my $obj = $self->obj; ... },
   },
);

如果访问者几乎完全相同,您可以执行类似

的操作
sub make_obj_accessor {
   my ($name) = @_;
   return sub {
      my $self = shift;
      my $obj = $self->obj;
      ... $name ...
   };
}

has obj => (
   is      => 'ro',
   handles => {
      (map make_obj_accessor($_), qw(
         val1
         val2
      ))
   },
);

当然,如果你真的只有哈希,那么你只需要

FOOBAR->new( %hash )