如何在Perl中有条件地导入包? [英] How can I conditionally import a package in Perl?
本文介绍了如何在Perl中有条件地导入包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Perl脚本,它使用一个不常见的模块,我希望它可以在没有安装该模块的情况下使用,但功能有限。有可能吗?
I have a Perl script which uses a not-so-common module, and I want it to be usable without that module being installed, although with limited functionality. Is it possible?
我想到这样的事情:
my $has_foobar;
if (has_module "foobar") {
<< use it >>
$has_foobar = true;
} else {
print STDERR "Warning: foobar not found. Not using it.\n";
$has_foobar = false;
}
推荐答案
你可以使用要求在运行时加载模块, eval 以捕获可能的异常:
You can use require to load modules at runtime, and eval to trap possible exceptions:
eval {
require Foobar;
Foobar->import();
};
if ($@) {
warn "Error including Foobar: $@";
}
另请参阅perldoc 使用。
See also perldoc use.
这篇关于如何在Perl中有条件地导入包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文