在Perl中Moo,您可以使用实现子around,这些子将包装类中的其他方法。
around INSERT => sub {
my $orig = shift;
my $self = shift;
print "Before the original sub\n";
my $rv = $orig->($self, @_);
print "After the original sub\n";
};
Run Code Online (Sandbox Code Playgroud)
您可以使用角色将方法隐藏起来,然后使用callwith:
class Foo {
method meth { say 2 }
}
my $foo = Foo.new but role :: {
method meth(|c) { say 1; callwith(|c); say 3 }
};
$foo.meth
Run Code Online (Sandbox Code Playgroud)
实现before(),after()和around()函数,这些函数可用于类似于Perl 5的Moose修改类方法。它在内部使用wrap(),并返回包装器处理程序,因此很容易对原始文件进行.restore()。
这是模块的实现方式around:
sub around ($class, $method-name, &closure) is export
{
$class.^find_method($method-name).wrap(method { closure(); });
}
Run Code Online (Sandbox Code Playgroud)
用 wrap
sub bar () { return "baþ" };
my $wrapped = &bar.wrap( { " ? " ~ callsame() ~ " ? " } );
say bar(); # OUTPUT: «? baþ ? »
Run Code Online (Sandbox Code Playgroud)
由于方法程序,你需要一个稍微更令人费解的方式来获得的方法本身就是一个手柄,但除此之外,该方法是完全一样的,因为Method小号是一个子类Routine小号
class Baz {
method bar () { return "baþ" };
}
my &method_bar = Baz.^find_method("bar");
my $wrapped = &method_bar.wrap( { " ? " ~ callsame() ~ " ? " } );
say Baz.bar(); # OUTPUT: «? baþ ? »
Run Code Online (Sandbox Code Playgroud)
这$wrapped是一个句柄,以后可以在需要时用来解开它。
编辑:添加代码以获取类方法的句柄,例如从此处获取。
| 归档时间: |
|
| 查看次数: |
164 次 |
| 最近记录: |