代码片段:
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/