开发者

How can I pass a instance method in Perl?

sub method_of_class_A {
    B->new(back => a_specific_met开发者_如何学Gohod_of_class_A)->run;
}

I want to pass current A instance a's a_specific_method_of_class_A to B's instance b so that b can goto a's a_specific_method_of_class_A

as if a->a_specific_method_of_class_A is called directly so that the stack doesn't accumulate.

How to do this kind of job in Perl?


Use the can method.


If you're asking what I think you're asking, you probably have to pass a closure:

sub method_of_class_A {
    my $self = shift;
    return B->new( 
          back => sub { $self->a_specific_method_of_class_A(); } 
        )->run;
}

and I think that's what you need because you do not seem to be passing an instance of $a to B.

If you need this a lot, you could assign it as a field in the object:

back =>  $self->{invoke_method_closure} 
     ||= sub { $self->a_specific_method_of_class_A(); } 

I'm not really sure how either of these ideas helps with the criteria "that the stack doesn't accumulate", because I'm not really sure what this criteria entails. The goto call will simply avoid adding 1 level to the stack. However, if you look at that block, you'll see what you're going to. And you'll jump to a instruction to invoke the method in a normal way. So that level that you "saved" is used anyway.

gotos are better not to try to prematurely optimize method invocation but to pass the stack to another handler with some wrapping behavior. So it works well enough in import methods which delegate to Exporter's basic behavior, or AUTOLOAD subs which try to figure out what the caller wants to do and then invoke the proper code with the passed arguments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜