Perl   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使用perl中的函数引用从包中执行函数?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用函数引用来动态执行其他包中的函数.

我一直在为这个想法尝试不同的解决方案,但似乎没有任何效果!
所以,我想问这个问题,并在尝试这样做时,解决方案有效!但我不确定这是否是正确的方法:它需要手动工作并且有点“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.有关详细信息,请参阅 @L_874_0@.
use Strict;
use warnings;
require Module;

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

大佬总结

以上是大佬教程为你收集整理的如何使用perl中的函数引用从包中执行函数?全部内容,希望文章能够帮你解决如何使用perl中的函数引用从包中执行函数?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。