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?
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?
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);
}
# ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With