使用 Moose 时如何获取方法引用
我试图弄清楚如何使用 Moose 获取方法代码引用。
下面是我正在尝试做的事情的示例:
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;
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我上面链接到的问题详细介绍了以下情况下的各种选项:将方法调用封装在代码引用中。在您的情况下,我会将
main
包编写为:$storage
更改为词法,以便代码引用sub {$storage->batch_store( @_)}
可以关闭它。添加到末尾的(@_)
允许将参数传递给方法。我不是 Moose 专家,但我相信您需要使用附加的取消引用箭头来调用代码:
这只是以下内容的简写:
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:$storage
is changed to a lexical so that the code referencesub {$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:
which is just shorthand for: