Search code examples
perlmoose

How does one get a method reference when using Moose


I'm trying to figure out how to get a method code reference using Moose.

Below is an example of what I'm trying to do:

use Modern::Perl;

package Storage;
use Moose;

sub batch_store {
  my ($self, $data) = @_;
  ... store $data ...
}

package Parser;
use Moose;

has 'generic_batch_store' => ( isa => 'CodeRef' );

sub parse {
  my $self = shift;
  my @buf;

  ... incredibly complex parsing code ...
  $self->generic_batch_store(\@buf);
}

package main;

$s = Storage->new;

$p = Parser->new;
$p->generic_batch_store(\&{$s->batch_store});

$p->parse;

exit;

Solution

  • The question I linked to above goes into detail about the various options when encapsulating a method call in a code ref. In your case, I would write the main package as:

    my $storage = Storage->new;
    
    my $parser = Parser->new;
    $parser->generic_batch_store(sub {$storage->batch_store(@_)});
    
    $parser->parse;
    

    $storage is changed to a lexical so that the code reference sub {$storage->batch_store(@_)} can close over it. The (@_) added to the end allows arguments to be passed to the method.

    I am not a Moose expert, but I believe that you will need to call the code with an additional dereferencing arrow:

    $self->generic_batch_store->(\@buf);
    

    which is just shorthand for:

    ($self->generic_batch_store())->(\@buf);