如何在Perl中有条件地使用模块? [英] How can I conditionally use a module in Perl?

查看:151
本文介绍了如何在Perl中有条件地使用模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Perl中做这样的事情:

I want to do something like this in Perl:

$Module1="ReportHashFile1"; # ReportHashFile1.pm
$Module2="ReportHashFile2"; # ReportHashFile2.pm

if(Condition1)
{
  use $Module1;
}
elsif(Condition2)
{
  use $Module2;
}

ReportHashFile * .pm包含一个包ReportHashFile *。

ReportHashFile*.pm contains a package ReportHashFile* .

另外如何根据动态模块名称引用模块内的数组?

Also how to reference an array inside module based on dynamic module name?

@Array= @$Module1::Array_inside_module;

无论如何我能做到这一点。某种编译器指令?

Is there anyway I can achieve this. Some sort of compiler directive?

推荐答案

你可能会发现 if 模块对此有用。

You might find the if module useful for this.

否则基本的想法是使用 require ,这在运行时发生,而不是使用,这在编译时发生。请注意'

Otherwise the basic idea is to use require, which happens at run-time, instead of use, which happens at compile-time. Note that '

BEGIN {
    my $module = $condition ? $Module1 : $Module2;
    my $file = $module;
    $file =~ s[::][/]g;
    $file .= '.pm';
    require $file;
    $module->import;
}

至于解决全局变量,如果你只是导出变量或者更容易将函数返回给调用者的函数,您可以通过其非限定名称使用它。否则,也可以使用方法并将其称为 $ Module-> method_name

As for addressing globals, it might be easier if you just exported the variable or a function returning it to the caller, which you could use by its unqualified name. Otherwise there's also the possibility of using a method and calling it as $Module->method_name.

或者,您可以使用 perlref 中记录的符号引用。然而,这通常是代码味道。

Alternatively, you could use symbolic references as documented in perlref. However, that's usually quite a code smell.

my @array = do {
    no strict 'refs';
    @{ ${ "${Module}::Array_inside_module" } };
};

这篇关于如何在Perl中有条件地使用模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆