moose around方法修饰符适用于多个属性,如何判断正在修改哪个属性?

时间:2014-10-09 20:55:32

标签: perl moose

假设像这样的Moose对象

package Foo;
use Moose;
has a => ( is => 'rw', isa => 'Int' );
has b => ( is => 'rw', isa => 'Str' );
has c => ( is => 'rw', isa => 'HashRef' );

around [ qw(a b c) ] => sub {
    my $orig = shift;
    my $self = shift;
    return $self->$orig() unless @_;
    my $aname = ???? # meta something?
    $self->myfunction($aname, @_);
};

如何将$aname设置为正在设置的属性的名称。换句话说,如果

$foo->a(2)

我希望能够将$aname设置为a

我可以为每个属性设置around,但这似乎是重复的。

1 个答案:

答案 0 :(得分:4)

一种方法是使用Moose::Manual::MethodModifiers #Wrapping multiple methods at once中建模的for循环:

for my $aname (qw(a b c)) {
    around $aname => sub {
        my $orig = shift;
        my $self = shift;
        return $self->$orig() unless @_;
        $self->myfunction( $aname, @_ );
    };
}