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

I wanted to use a function reference to dynamically execute functions from other packages.

I was looking for different solutions for the idea, and nothing worked! So, I thought about asking this question, and trying to do it worked . but I’m not sure if this is the right way: it requires manual work and is a bit “hacked.” "Can it be improved?

  • Feature Support Package

    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. The script utility should use the package using the function

    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 works! However, is there a way to improve it?

+5
source share
2

can. . perldoc UNIVERSAL.

use strict;
use warnings;
require Module;

sub ExecuteCommand {
    my ($InputCommand, @Arguments) = @_;
    if (my $ref = Module->can($InputCommand)) {
        $ref->(@Arguments);
    }
    # ...
}
+4

. , , . can , - OO-ish, , , , .

, ) Perl, ( // , Perl // 5.10- "" , ") b) :

Module.pm

package Module;

use strict;
use warnings;
use 5.010;

our $function_lookup = {
    FctInitEvaluate => \&init_evaluate,
    FctInitExecute  => \&init_execute,
};

sub init_evaluate {
    say 'In init_evaluate';
}

sub init_execute {
    say 'In init_execute';
}

1;

script.pl

#!/usr/bin/env perl

use strict;
use warnings;

require Module;

execute_command('FctInitEvaluate', 'Some input');
execute_command('FctInitExecute',  'Some input');

sub execute_command {
    my ($input_command, @arguments) = @_;
    $Module::function_lookup->{$input_command}(@arguments)
      if exists($Module::function_lookup->{$input_command});
}
0

All Articles