Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute functions from packages using function reference in perl?

I wanted to use function reference for dynamically executing functions from other packages.

I have been trying different solutions for a while for the idea and nothing seemed to work! So, i thought of asking this question and while attempting to do so, solution worked! but I'm not sure if it's the correct way to do so: it requires manual work and is a bit "hacky". Can it be improved?

  1. A package to support required functionality

    package Module;
    
    # $FctHash is intended to  be a Look-up table, on-reception 
    # of command.. execute following functions
    
    $FctHash ={
        'FctInitEvaluate' => \&FctInitEvaluate,
        'FctInitExecute' => \&FctInitExecute
    };
    
    sub FctInitEvaluate()
    {
        //some code for the evalute function
    }
    
    sub FctInitExecute()
    {
        //some code for the execute function
    }
    1;
    

2. Utility Script needs to use the package using function reference

    use strict;
    use warnings 'all';
    no strict 'refs';

    require Module;

    sub ExecuteCommand()
    {
      my ($InputCommand,@Arguments) =@_;
      my $SupportedCommandRefenece = $Module::FctHash;
         #verify if the command is supported before 
         #execution, check if the key is supported
         if(exists($SupportedCommandRefenece->{$InputCommand}) )
         {
           // execute the function with arguments
           $SupportedCommandRefenece->{$InputCommand}(@Arguments);
         }
      }

      # now, evaluate the inputs first and then execute the function
      &ExecuteCommand('FctInitEvaluate', 'Some input');
      &ExecuteCommand('FctInitExecute', 'Some input');
    }

But now, this technique seems to work! Still, is there a way to improve it?

like image 803
The_Unseen Avatar asked Oct 12 '22 02:10

The_Unseen


1 Answers

You can use can. Please see perldoc UNIVERSAL for details.

use strict;
use warnings;
require Module;

sub ExecuteCommand {
    my ($InputCommand, @Arguments) = @_;
    if (my $ref = Module->can($InputCommand)) {
        $ref->(@Arguments);
    }
    # ...
}
like image 154
yibe Avatar answered Oct 21 '22 07:10

yibe