如果已安装,如何需要可选的 Perl 模块? [英] How can I require an optional Perl module if installed?
问题描述
我有 Perl 代码,它依赖于 Term::ReadKey
来获取终端宽度.我的安装缺少这个模块,所以如果模块不存在,我想提供一个默认值,而不是抛出异常.
如何有条件地使用可选模块,而无需提前知道它是否可用.
# 但仅当模块已安装并存在时使用 Term::ReadKey;...
我怎样才能做到这一点?
这是一个不需要其他模块的基本解决方案:
我的 $rc = eval{需要 Term::ReadKey;Term::ReadKey->import();1;};如果($rc){# Term::ReadKey 加载并成功导入...}
请注意,以下所有使用 eval { use SomeModule }
的答案(我希望它们低于这个答案!:-)都是错误的,因为对 use
语句进行了评估在编译时,无论它们出现在代码的哪个位置.因此,如果 SomeModule
不可用,脚本将在编译后立即死亡.
(use
语句的字符串 eval 也可以工作(eval 'use SomeModule';
),但是在运行时解析和编译新代码是没有意义的require
/import
对执行相同的操作,并在编译时进行语法检查以启动.)
最后,请注意我在此使用 eval { ... }
和 $@
就本示例而言是简洁的.在实际代码中,您应该使用类似 Try::Tiny 之类的东西,或者至少 注意它解决的问题.>
I have Perl code which relies on Term::ReadKey
to get the terminal width. My installation is missing this module, so I want to provide a default if the module isn't present rather than throw an exception.
How can I conditionally use an optional module, without knowing ahead of time whether it is available.
# but only if the module is installed and exists
use Term::ReadKey;
...
How can I accomplish this?
Here's a bare-bones solution that does not require another module:
my $rc = eval
{
require Term::ReadKey;
Term::ReadKey->import();
1;
};
if($rc)
{
# Term::ReadKey loaded and imported successfully
...
}
Note that all the answers below (I hope they're below this one! :-) that use eval { use SomeModule }
are wrong because use
statements are evaluated at compile time, regardless of where in the code they appear. So if SomeModule
is not available, the script will die immediately upon compiling.
(A string eval of a use
statement will also work (eval 'use SomeModule';
), but there's no sense parsing and compiling new code at runtime when the require
/import
pair does the same thing, and is syntax-checked at compile time to boot.)
Finally, note that my use of eval { ... }
and $@
here is succinct for the purpose of this example. In real code, you should use something like Try::Tiny, or at least be aware of the issues it addresses.
这篇关于如果已安装,如何需要可选的 Perl 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!