How does one get a method reference when using Moose

浪子不回头ぞ 提交于 2020-01-02 12:59:11

问题


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;

回答1:


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);


来源:https://stackoverflow.com/questions/4870070/how-does-one-get-a-method-reference-when-using-moose

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!