加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何使用perl中的函数引用从包中执行函数?

发布时间:2020-12-15 21:45:06 所属栏目:大数据 来源:网络整理
导读:我想使用函数引用来动态执行其他包中的函数. 我一直在为这个想法尝试不同的解决方案,但似乎没有任何效果! 所以,我想问这个问题,并在尝试这样做时,解决方案有效!但我不确定这是否是正确的方法:它需要手动工作并且有点“hacky”.可以改进吗? 支持所需功能
我想使用函数引用来动态执行其他包中的函数.

我一直在为这个想法尝试不同的解决方案,但似乎没有任何效果!
所以,我想问这个问题,并在尝试这样做时,解决方案有效!但我不确定这是否是正确的方法:它需要手动工作并且有点“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.实用程序脚本需要使用函数引用来使用该包

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');
    }

但现在,这种技术似乎有效!不过,有没有办法改善它?

解决方法

你可以用can.有关详细信息,请参阅 perldoc UNIVERSAL.
use strict;
use warnings;
require Module;

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读