在 around 方法修饰符周围传递变量

发布于 2024-09-14 02:13:33 字数 682 浏览 25 评论 0原文

是否可以在多次调用之间传递变量到 around MethodModier?示例(这不起作用,但希望传达我想要做的事情)

sub mysub { ... };

around 'mysub' => sub {
   my $orig = shift;
   my $self = shift;

   my $value = get_value;

   $self->orig(@_);
};

around 'mysub' => sub {
   my $orig = shift;
   my $self = shift;
   my $value = shift;

   my $output
       = "sometext $value"
       . $self->orig(@_);
       . 'someothertext $value'
       ;
};

我最终希望将这些“周围”放置在可插入特征中,我不会真正知道预先加载了哪些特征,但最终输出将是格式整齐。

我的想法可能完全错误,所以欢迎其他建议。

Is it possible to pass variables between multiple calls to the around MethodModier? example (that doesn't work but hopefully conveys what I want to do)

sub mysub { ... };

around 'mysub' => sub {
   my $orig = shift;
   my $self = shift;

   my $value = get_value;

   $self->orig(@_);
};

around 'mysub' => sub {
   my $orig = shift;
   my $self = shift;
   my $value = shift;

   my $output
       = "sometext $value"
       . $self->orig(@_);
       . 'someothertext $value'
       ;
};

I'd eventually like to have these 'arounds' placed in pluggable traits, where I won't really know which ones are loaded beforehand but the final output will be neatly formatted.

It's possible that I'm thinking about this completely wrong, so other suggestions welcome.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

莫多说 2024-09-21 02:13:33

你试图做的事情没有逻辑。

“周围修饰符接收
原始方法作为其第一个参数,
然后是对象,最后是任何
传递给该方法的参数。”

https://metacpan .org/pod/Moose::Manual::MethodModifiers#BEFORE-AFTER-AND-AROUND

What you are trying to do don't have logic.

"An around modifier receives the
original method as its first argument,
then the object, and finally any
arguments passed to the method."

https://metacpan.org/pod/Moose::Manual::MethodModifiers#BEFORE-AFTER-AND-AROUND

一身仙ぐ女味 2024-09-21 02:13:33

使用实例变量:

$self->{value} = get_value;
...
my $value = $self->{value};

(请参阅问题评论以获取实际答案。我只是在这里重申,因此我可以接受答案,感谢:

jmz)

Use an instance variable:

$self->{value} = get_value;
...
my $value = $self->{value};

(See question commments for an actual answer. I'm just reiterating it here, so I can accept an answer, thanks to:

jmz)

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