perl5ever has asked for the wisdom of the Perl Monks concerning the following question:

Suppose I have an object with an instance variable 'data'.
package Foo; use Moose; has data (is => 'rw');

The 'data' field is meant to populated with a hash ref.

Is is possible to delegate some accessors of Foo to the 'data' hash ref. E.g.:

my $foo = Foo->new(data => { this => 1, that => 2 }); $foo->this # returns $foo->data->{this} $foo->that(10) # sets $foo->data->{that} = 10
The delegated fields will be known in advance.

It seems that Moose::Meta::Attribute::Native is somewhat relevant here, but I don't see how it would be done.

Replies are listed 'Best First'.
Re: delegate Moose accessors to a HASH?
by ikegami (Patriarch) on Jun 23, 2011 at 19:26 UTC
    handles => { this => sub { $_[0]->data->{this} }, that => sub { $_[0]->data->{that} }, },
      The setter doesn't seem to work:
      $foo->that(10) # sets $foo->data->{that} = 10

      I can make this work:

      $foo->that = 10
      by adding :lvalue to the sub declarations, but that's not what I want.

        Sorry, I wrote it as a getter, not an accessor.

        handles => { this => sub { @_ == 1 ? $_[0]->data->{this} : $_[0]->data->{this} = $_[1] }, that => sub { @_ == 1 ? $_[0]->data->{that} : $_[0]->data->{that} = $_[1] }, },

        You can use a map to avoid duplication and/or an accessor generating function.