简体   繁体   English

如何在 Raku 中实现周围

[英]How to implement around in Raku

In Perl, using Moo , you can implement around subs, which will wrap around other methods in a class.在 Perl 中,使用Moo可以实现around subs,这将围绕 class 中的其他方法。

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";
};

How can this behaviour be implemented in Raku , preferably using a role ?如何在Raku中实现这种行为,最好使用role

You can shadow the method with the role and then use callwith :您可以使用角色隐藏方法,然后使用callwith

class Foo {
    method meth { say 2 }
}

my $foo = Foo.new but role :: {
    method meth(|c) { say 1; callwith(|c); say 3 }
};

$foo.meth

Method::Modifiers方法::修饰符

Implements before(), after() and around() functions that can be used to modify class methods similarly to Perl 5's Moose.实现 before()、after() 和 around() 函数,可用于修改 class 方法,类似于 Perl 5 的 Moose。 It uses wrap() internally, and returns the wrapper handler, so it is easy to.restore() the original.它在内部使用 wrap(),并返回 wrapper 处理程序,因此很容易 to.restore() 原始。

This is how the module implements around :这就是模块实现around方式:

sub around ($class, $method-name, &closure) is export
{
  $class.^find_method($method-name).wrap(method { closure(); });
}

Use wrap使用wrap

sub bar () { return "baþ" };

my $wrapped = &bar.wrap( { " → " ~ callsame() ~ " ← " } );

say bar(); # OUTPUT:  «→ baþ ← »

Since methods are routines, you'll need a slightly more convoluted way to get a handle on the method itself, but other than that, the method is exactly the same, since Method s are a subclass of Routine s由于方法是例程,因此您需要一种稍微复杂的方法来处理方法本身,但除此之外,方法完全相同,因为MethodRoutine子类

class Baz {
    method bar () { return "baþ" };
}

my &method_bar = Baz.^find_method("bar");
my $wrapped = &method_bar.wrap( { " → " ~ callsame() ~ " ← " } );

say Baz.bar(); # OUTPUT:  «→ baþ ← »

The $wrapped is a handle that can be used, later on, to unwrap it if needed. $wrapped是一个句柄,稍后可以在需要时打开它。

Edit : to add the code to get a handle on the class method, taken from here , for instance.编辑:添加代码以获取 class 方法的句柄,例如,取自此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM