我想检测用户何时缺少必需的模块并打印一条友好的错误消息,说明他们需要安装什么。
到目前为止,我尝试将其放在脚本的开头:
eval {
use IO::Uncompress::Gunzip qw(gunzip $GunzipError) ;
};
if ($@) {
die "Error: IO::Uncompress::Gunzip not installed: $@";
}
但是 Perl 似乎死在“使用”行而不是“死”行上,并且从不打印我的错误消息。
最佳答案
use IO::Uncompress::Gunzip qw( gunzip $GunzipError );
简称
BEGIN {
require IO::Uncompress::Gunzip;
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
}
和
BEGIN
block 在编译后立即进行评估。这意味着您的代码可以:eval
陈述。BEGIN
堵塞。require IO::Uncompress::Gunzip;
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
BEGIN
堵塞。require IO::Uncompress::Gunzip;
import IO::Uncompress::Gunzip qw( gunzip $GunzipError );
if
陈述。 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: $@";
}
(我希望有一种很好的方法来找出是否安装了模块。即使第一个解决方案也会捕获其他错误,第二个甚至更多。)
关于Perl - eval 不捕获 "use"语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11020911/