How do I implement a dispatch table in a Perl OO module?

后端 未结 4 767
轮回少年
轮回少年 2020-12-31 15:21

I want to put some subs that are within an OO package into an array - also within the package - to use as a dispatch table. Something like this

package Blah:         


        
4条回答
  •  既然无缘
    2020-12-31 16:20

    use lib Alpha;
    
    my $foo = Alpha::Foo->new; # indirect object syntax is deprecated
    
    $foo->bar();
    
    my %disp_table = ( bar => sub { $foo->bar() } );
    
    $disp_table{bar}->(); # call it
    

    You need a closure because you want to turn a method call into an ordinary subroutine call, so you have to capture the object you're calling the method on.

提交回复
热议问题