使用 Moose 时如何获取方法引用 [英] How does one get a method reference when using Moose
问题描述
我正在尝试弄清楚如何使用 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;
推荐答案
The我上面链接的问题详细介绍了在代码引用中封装方法调用时的各种选项.在您的情况下,我会将 main
包编写为:
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
更改为词法,以便代码引用 sub {$storage->batch_store(@_)}
可以关闭它.添加到末尾的 (@_)
允许将参数传递给方法.
$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.
我不是 Moose 专家,但我相信您需要使用额外的取消引用箭头来调用代码:
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);
这只是以下的简写:
($self->generic_batch_store())->(\@buf);
这篇关于使用 Moose 时如何获取方法引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!