如何在Moose属性编写器中合并HashRef?

时间:2013-11-26 10:56:37

标签: perl moose

有一个简单的示例代码

use Modern::Perl;
use Data::Dumper;

package My;
use Moose;
use Method::Signatures::Simple;
has 'result' => (
    is => 'rw',
    isa => 'HashRef',
    default => sub{{}},
    clearer => 'clear_result'
);

method run {
    $self->clear_result;                 #clearing the result
    $self->result( $self->run_part1 );
    $self->do_something;
    $self->result( $self->run_part3 );   #need merge
}

method do_something {
    $self->result( $self->run_part2 );   #need merge
}

method run_part1 { return { aaa => 'aaa' } }
method run_part2 { return { bbb => 'bbb' } }
method run_part3 { return { ccc => 'ccc' } }

package main;
my $p = My->new;
say Dumper $p->run;

结果(当然)是:

$VAR1 = {
          'ccc' => 'ccc'
        };

我想要结果:

$VAR1 = {
          'aaa' => 'aaa'
          'bbb' => 'bbb'
          'ccc' => 'ccc'
        };

所以,问题是 - 如何在设置时合并$self->result HashRef?

是的,我可以添加新的方法add_result,如:

method add_result($hr) {
    use Hash::Merge::Simple qw(merge);
    $self->result( merge $self->result, $hr );
}
我的代码中的

无处不在 $self->result$self->add_result,但想知道是否还有其他解决方案......

1 个答案:

答案 0 :(得分:3)

has 'result' => (
    acccessor => '_result',
    isa => 'HashRef',
    default => sub{{}},
    clearer => 'clear_result'
);

sub result {
    my $self = shift;
    if (@_) {
        my ($hr) = @_;
        return $self->_result( ... merged hash ...);
    } else {
        return $self->_result();
    }   
}