我想检测用户何时缺少所需的模块,并打印一条友好的错误消息,解释他们需要安装的内容。
到目前为止,我尝试将其放在脚本的开头:
eval {
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
};
if ($@) {
die "Error: IO::Uncompress::Gunzip not installed: $@";
}
但 Perl 似乎死在“use”行而不是“die”行,并且从不打印我的错误消息。
use IO::Uncompress::Gunzip qw( gunzip $GunzipError );
是缩写
BEGIN {
require IO::Uncompress::Gunzip;
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
}
and BEGIN
块在编译后立即进行评估。这意味着您的代码会:
- Compilation phase:
- Compile
eval
statement.
- Compiled
BEGIN
block.
- Compile
require IO::Uncompress::Gunzip;
- Compile
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
- Evaluate
BEGIN
block.
- 评价
require IO::Uncompress::Gunzip;
- 评价
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
- Compile
if
陈述。
- Run phase:
- 评价(空)
eval
陈述。
- 评价
if
陈述。
如果步骤1.1.2.1发生异常,eval
在步骤 2.1 中运行不会捕获它!
解决方案:
你从相当于的东西开始
BEGIN {
require IO::Uncompress::Gunzip;
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
}
这是来自的错误require
你想抓住,所以只需添加一个eval
周围的require
:
BEGIN {
eval { require IO::Uncompress::Gunzip }
or die "Error: IO::Uncompress::Gunzip not installed: $@";
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
}
您也可以推迟use
通过使用进行编译(并因此评估)eval EXPR
代替eval BLOCK
:
BEGIN {
eval 'use IO::Uncompress::Gunzip qw( gunzip $GunzipError ); 1'
or die "Error: IO::Uncompress::Gunzip not installed: $@";
}
(我希望有一种好方法来确定模块是否已安装。即使第一个解决方案也会捕获其他错误,第二个解决方案甚至更多。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)