2012-05-02 107 views
-1

我在perl项目上工作,我必须动态地使用perl模块。我有以下模块称为CT.pm:动态使用perl模块

sub new { 
    my $class = shift; 
    my ($debug, $debug_matches,%checkHash) = @_; 
    my $self = {}; 
    $self->{DEBUG} = shift; 
    $self->{DEBUG_MATCHES} = shift; 
    $self->{CHECKRESULT_OK} = "COMPLIANT"; 
    $self->{CHECKRESULT_ERROR} = "NONCOMPLIANT"; 
    %{$self->{checkHash}} = %checkHash; 

    eval{ 
     use $checkHash{"type"}; 
     $check = $checkHash{"type"}->new($self->{DEBUG},$self->{DEBUG_MATCHES},%checkHash); 
    }; 

    bless($self,$class); 
    return $self; 
} 

此构造函数获取名为%checkHash作为参数的散列。这个散列有一个叫做类型的键。此键映射到我想要动态使用的perl模块的名称的值。

我想出了以下的方法来做到这一点:(我知道不会工作,我也知道人们说,EVAL是坏的):

eval{ 
    use $checkHash{"type"}; 
    $check = $checkHash{"type"}->new($self->{DEBUG},$self->{DEBUG_MATCHES},%checkHash); 
}; 

但这个想法是动态使用perl模块,名称为$ checkHash {“type”}。

如果任何人有任何想法如何做到这一点请帮助:) thx! :D

+0

找到了一种方法 - 不能在8小时内发布任何解决方案。 – Diemauerdk

+2

这已被讨论过:http://stackoverflow.com/questions/251694/how-can-i-check-if-i-have-a-perl-module-before-using-it http:// stackoverflow。 com/questions/1094125/try-to-use-module-in-perl-and-print-message-if-module-not-available http://stackoverflow.com/questions/1917261/how-can-i-dynamically -include-perl-modules http://stackoverflow.com/questions/2855207/how-do-i-load-a-module-at-runtime http://stackoverflow.com/questions/3470706/perl-dynamically-include http://stackoverflow.com/questions/3945583/how-can-i-conditionally-use http://stackoverflow.com/questions/6855970/use-of-eval – daxim

回答

1

您的eval是一个“block eval”,它实际上只是Perl中的一个异常捕获机制,缺乏与通常的“字符串评估”相关的任何耻辱感。您可以通过eval "require $checkHash{'type'}"动态加载字符串eval的模块。如果您希望完全避免使用字符串评估,您只需手动将裸字模块名称转换为.pm文件路径即可。你还是应该使用块的eval捕捉模块装入异常:

my $file = $class . '.pm'; 
$file =~ s{::}{/}g; 
eval { require $file }; 
if([email protected]){ die "failed to load $class: [email protected]" } 

这仍然不会运行加载的类import方法。您需要将课程路径分解为片段并手动查找。对于OO类,这也经常可以安全地跳过。