Pass variables around the around method modifier

梦想与她 提交于 2019-12-02 08:23:46

问题


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.


回答1:


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




回答2:


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:

)



来源:https://stackoverflow.com/questions/3486932/pass-variables-around-the-around-method-modifier

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