【发布时间】:2011-05-09 22:55:17
【问题描述】:
我想使用函数引用来动态执行其他包中的函数。
我一直在尝试不同的解决方案来解决这个想法,但似乎没有任何效果! 所以,我想问这个问题,在尝试这样做时,解决方案奏效了! 但我不确定这是否是正确的方法:它需要手动工作并且有点“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;
2。 Utility Script 需要使用包 using 函数参考
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');
}
但现在,这项技术似乎奏效了!不过,有没有办法改进它?
【问题讨论】:
-
Perl 不是 JavaScript。你用“#”而不是“//”来引入注释。带有“sub”声明的行上的括号并不像您认为的那样。消除它们,例如 sub ExecuteCommand {...}
-
函数调用 (
&ExecuteCommand(...)) 上的和号前缀也不会像您认为的那样。也消除它们。 -
@Dave,实际上,我修改了他的代码使其看起来 (a) 可读 (b) Perl。但现在我有疑问:也许是 JavaScript...
-
@Pavel:我查看了问题修订历史中的原始版本,不,从一开始就是 Perl-code-trying-to-use-//-cmets。你没有破坏它,它一开始就被破坏了。 :)
标签: perl module reference package