使用 Moose 时如何获取方法引用

发布于 2024-10-15 13:18:46 字数 553 浏览 7 评论 0原文

我试图弄清楚如何使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏舞 2024-10-22 13:18:46

我上面链接到的问题详细介绍了以下情况下的各种选项:将方法调用封装在代码引用中。在您的情况下,我会将 main 包编写为:

my $storage = Storage->new;

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

$parser->parse;

$storage 更改为词法,以便代码引用 sub {$storage->batch_store( @_)} 可以关闭它。添加到末尾的 (@_) 允许将参数传递给方法。

我不是 Moose 专家,但我相信您需要使用附加的取消引用箭头来调用代码:

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

这只是以下内容的简写:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文