perl - 如何处理终止的 perl 构造函数?

标签 perl error-handling die

代码片段:

my $tz = DateTime::TimeZone->new(name => 'America/San_Francisco');

这会立即消失,因为 America/San_Francisco 不是 recognized timezone .

打印以下消息:

时区“America/San_Francisco”无法加载,或者是一个无效名称。

我想在脚本退出之前处理此错误并为用户打印附加信息。我尝试使用unless,但没能捕获die

如何做到这一点?

最佳答案

使用 eval { ... }$@ 捕获和管理 fatal error 。

my $tz = eval { DateTime::TimeZone->new(name => 'America/San_Francisco') };
if (!$tz) {
    if ($@ =~ /The timezone .* could not be loaded/) {
        warn "Choose a timezone from ", 
            "https://en.wikipedia.org/wiki/List_of_tz_database_time_zones#List";
    } else {
        warn "Error in DateTime::TimeZone constructor: $@";
    }
    exit 1;
}

关于perl - 如何处理终止的 perl 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553388/

相关文章:

regex - perl 正则表达式 : how to escape backslash character

perl - 我怎样才能使 WWW :Mechanize to not fetch pages twice?

perl - 在 foreach 循环中死亡时未按良好顺序执行的行

java - 无法从静态上下文引用非静态方法count(int)

perl - block 评估的替代方案?

PHP:杀死脚本还是提前返回?

perl - "map"如何解释它在 Perl 中的第一个参数?

python - perl 中的多个哈希分配 - 转换为 python?为什么总是等于 1?

php - CakePHP : Customized error message should display on the same page instead of moving some other page

php - 如何修复PHP中的以下错误?