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

后端 未结 4 772
轮回少年
轮回少年 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 15:55

    There are a few ways to do this. Your third approach is closest. That will store a reference to the two subs in the array. Then when you want to call them, you have to be sure to pass them an object as their first argument.

    Is there a reason you are using the use fields construct?

    if you want to create self contained test subs, you could do it this way:

    $$self{test} = [ 
         map {
             my $code = $self->can($_); # retrieve a reference to the method
             sub {                  # construct a closure that will call it
                 unshift @_, $self; # while passing $self as the first arg
                 goto &$code;   # goto jumps to the method, to keep 'caller' working
             }    
         } qw/_sub1 _sub2/                  
     ];
    

    and then to call them

    for (@{ $$self{test} }) {
        eval {$_->(args for the test); 1} or die $@;
    } 
    

提交回复
热议问题