如何避免程序崩潰?
Perl使用eval
用於捕集錯誤:
use strict;
use warnings;
use 5.016;
use Text::Iconv;
my $source_encoding = 'blabla';
my $result_encoding = 'utf-8';
my $converter = eval {
Text::Iconv->new(
$source_encoding,
$result_encoding
);
}; #Error message gets inserted into [email protected]
if (not $converter and [email protected] =~ /invalid argument/i) {
say "Either the '$source_encoding' encoding or the ",
"'$result_encoding' encoding\nis not available on this system.";
}
if ($converter) { #Can new() fail in other ways?
my $result = $converter->convert('€');
if (not $result) {
say "Some characters in '$source_encoding'\n",
"are invalid in '$result_encoding'.";
}
else {
say $result;
}
}
在[塊]的形式中,塊中的代碼被解析一次 - 同時周圍本身被解析中的eval的代碼 - 並在當前Perl程序的上下文中執行。這種形式通常用於比第一個更有效地捕獲異常(見下文),同時還提供了在編譯時檢查BLOCK內代碼的好處。
http://perldoc.perl.org/functions/eval.html
或如何檢查支持的代碼轉換之前設置? (我知道的「的iconv --list」讀它在OS ,但必須有更好的解決辦法(希望))
這有什麼不好iconv --list
?
use strict;
use warnings;
use 5.016;
use Text::Iconv;
my $source_encoding = 'blabla';
my $result_encoding = 'utf-8';
my $available_encodings = `iconv --list`; #Backticks return a string.
my @encodings_arr = split /\s+/, $available_encodings;
my %encodings_set = map {lc $_ => undef} @encodings_arr;
my $source_encoding_available = exists $encodings_set{$source_encoding};
my $result_encoding_available = exists $encodings_set{$result_encoding};
if($source_encoding_available
and $result_encoding_available) {
say "Ready to convert";
}
else {
if (not $source_encoding_available) {
say "'$source_encoding' encoding not available.";
}
if (not $result_encoding_available) {
say "'$result_encoding' encoding not available.";
}
}