Title;
I have a Perl class, let's call it Foo
, and I would like to conditionally and automatically (automatically as in: without changing the implementation of its methods) wrap some of its instances' methods (not the class' methods!) in a subroutine that, on one of the methods' invokation, will do some stuff before calling the target method itself.
Example:
package Foo;
sub new {
my $self = bless({}, shift);
my $wrap = shift;
# I want to conditionally wrap **the blessed reference's**
# methods here, based on a list of methods names, depending on
# the value of $wrap; this is done so that the caller can decide
# whether to wrap its own instance's methods or not, and so
# that, if it decides to do so, a subroutine will run **before**
# a method listed in the list of methods is run
return $self;
}
sub method1 {
return;
}
sub method2 {
return;
}
# [...]
The wrapper should have access to the arguments passed by the caller to the target method (such as 'foo'
and 'bar'
in Foo -> method1('foo', 'bar')
)
What I've tried:
Hook::LexWrap
: it works fine, but it can only transparently wrap class methods (not what I want, as wrapping the class' methods defeats the purpose of wrapping only some specific instances' methods); it can wrap anonymous subroutines, however, in that case, it will return a reference to the wrapped subroutine, which defeats the purpose of automatically wrapping the methods;Perinci::Sub::Wrapper
: I didn't really try this, as it appears to also return a reference to the wrapped subroutine;- I looked at another module, which I can't recall the name of. That also suffered from one of these two problems.
I'll gladly accept a module suggestion as well as a simple idea on how to implement this myself (just the idea is fine, I should be able to implement it myself as long as I'm pointed in the right direction).