The*_*een 5 perl module reference package
我想使用函数引用来动态执行其他包中的函数.
我一直在为这个想法尝试不同的解决方案,但似乎没有任何效果!所以,我想问这个问题,并在尝试这样做时,解决方案有效!但我不确定这是否是正确的方法:它需要手动工作并且有点"hacky".可以改进吗?
用于支持所需功能的包
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;
Run Code Online (Sandbox Code Playgroud)2.实用程序脚本需要使用函数引用来使用该包
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');
}
Run Code Online (Sandbox Code Playgroud)
但现在,这种技术似乎有效!不过,有没有办法改善它?
您可以使用can。perldoc UNIVERSAL详情请参阅。
use strict;
use warnings;
require Module;
sub ExecuteCommand {
my ($InputCommand, @Arguments) = @_;
if (my $ref = Module->can($InputCommand)) {
$ref->(@Arguments);
}
# ...
}
Run Code Online (Sandbox Code Playgroud)