Search code examples
perlmoose

A moose around method modifier applies to several attributes, how do I tell which attribute is being modified?


Assuming a Moose object like this

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, @_);
};

How do I set $aname to be the name of the attribute that is being set. In other words, if

$foo->a(2)

I want to be able set $aname to a.

I could set an around for each attribute but that seems to be repetitive.


Solution

  • One method would be to use a for loop as modeled in Moose::Manual::MethodModifiers #Wrapping multiple methods at once:

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