标题;
我有一个 Perl 类,让我们称之为
Foo
,我想有条件地自动(自动如:不更改其方法的实现)包装 它的一些实例的方法(不是类的方法) !)在一个子例程中,在调用其中一个方法时,将在调用目标方法本身之前执行一些操作。
示例:
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;
}
# [...]
包装器应该能够访问调用者传递给目标方法的参数(例如
'foo'
中的 'bar'
和 Foo -> method1('foo', 'bar')
)
我尝试过的:
Hook::LexWrap
:它工作得很好,但它只能透明地包装类方法(不是我想要的,因为包装类的方法违背了仅包装某些特定实例的方法的目的);它可以包装匿名子例程,但是,在这种情况下,它将返回对包装子例程的引用,这违背了自动包装方法的目的;Perinci::Sub::Wrapper
:我并没有真正尝试过这个,因为它似乎还返回对包装子例程的引用;我很乐意接受模块建议以及关于如何自己实现这一点的简单想法(这个想法很好,只要我指向正确的方向,我应该能够自己实现它)。
Perl 的对象系统没有特定于实例的方法。所有方法都来自类,包括类方法 (
Class->foo
) 和实例方法 ($obj->foo
)。
由于您似乎有一个要覆盖的每个实例方法的固定列表,因此您可以使用如下所示的内容:
package Foo;
sub new {
my $class = shift;
my $self = bless( {}, $class );
$self->{ method1 } = sub { ... };
$self->{ method2 } = sub { ... };
return $self;
}
sub method1 { shift->{ method1 }->( @_ ) }
sub method2 { shift->{ method2 }->( @_ ) }
1