如何有条件地使用 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
,它发生在运行时,而不是use
,它发生在编译时.注意'
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" } };
};