如何有条件地使用 Perl 中的模块?
我想在 Perl 中做这样的事情:
$Module1="ReportHashFile1"; # ReportHashFile1.pm
$Module2="ReportHashFile2"; # ReportHashFile2.pm
if(Condition1)
{
use $Module1;
}
elsif(Condition2)
{
use $Module2;
}
ReportHashFile*.pm 包含一个包 ReportHashFile* 。
另外如何根据动态模块名称引用模块内部的数组?
@Array= @$Module1::Array_inside_module;
无论如何我可以实现这个目标吗?某种编译器指令?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能会发现
if
模块对此很有用。否则,基本思想是使用在运行时发生的
require
,而不是在编译时发生的use
。请注意,'至于寻址全局变量,如果您只是导出变量或将其返回给调用者的函数,则可能会更容易,您可以通过其非限定名称来使用它。否则,也可以使用方法并将其调用为
$Module->method_name
。或者,您可以使用
perlref
中记录的符号引用。然而,这通常是一种代码味道。You might find the
if
module useful for this.Otherwise the basic idea is to use
require
, which happens at run-time, instead ofuse
, which happens at compile-time. Note that '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
.Alternatively, you could use symbolic references as documented in
perlref
. However, that's usually quite a code smell.除非执行速度很重要,否则可以使用字符串 eval:
Unless the execution speed is important, you can use string eval:
人们已经告诉过您如何使用 Perl 原语加载模块。还有Module::Load::Conditional。
如果您希望访问同名的数组,无论您加载哪个模块,请考虑为此创建一个方法,以便您可以跳过符号引用内容。为每个模块提供一个同名的方法:
然后,当您加载该模块时:
2023 update 最近我一直在
state
中使用require
> 表达式,因为这只在范围内发生一次:我不知道你真正在做什么 (XY 问题),但可能有更好的设计。当事情看起来像这样棘手时,通常是因为您忽略了更好的解决方法。
People have already told you how you can load the module with Perl primitives. There's also Module::Load::Conditional.
If you're looking to access an array of the same name no matter which module you loaded, consider making a method for that so you can skip the symbolic reference stuff. Give each module a method of the same name:
Then, when you load that module:
2023 update Lately I've been using
require
in astate
expression since that only happens once in the scope:I don't know what you're really doing (XY Problem), but there's probably a better design. When things seem tricky like this, it's usually because you're overlooking a better way to to it.
也许有帮助...
调试的小例子。
使用
sub DEBUG () {1};
输出sub DEBUG () {0};
qv
perldoc.perl.org/if
Maybe helpful...
A little example for debugging.
Output with
sub DEBUG () {1};
Output with
sub DEBUG () {0};
q.v.
perldoc.perl.org/if