我得到了一个文件,(可能)以 Latin-1 (ISO 8859-1) 编码,并且需要对其进行一些转换和数据挖掘。输出应该是 UTF-8,我已经尝试了我能找到的关于 Perl 编码转换的任何内容,但没有一个产生任何可用的输出。
我知道use utf8;
什么都不做。我试过 Encode
包,看起来很有希望:
open FILE, '<', $ARGV[0] or die $!;
my %tmp = ();
my $last_num = 0;
while (<FILE>) {
$_ = decode('ISO-8859-1', encode('UTF-8', $_));
chomp;
next unless length;
process($_);
}
我尝试了我能想到的任何组合,也被扔进了
binmode(STDOUT, ":utf8");
, open FILE, '<:encoding(ISO-8859-1)', $ARGV[0] or die $!;
以及更多。结果要么是乱码,要么是像 \xC3 is not a valid UTF-8 character
这样的错误信息。 ,甚至是混合文本(有些是 UTF-8,有些是 Latin-1)。我想要的只是一种简单的方法来读取 Latin-1 文本文件并通过
print
在控制台上生成 UTF-8 输出.在 Perl 中有什么简单的方法可以做到这一点吗?
最佳答案
见 Perl encoding introduction和 Unicode cookbook .
$ piconv -f Latin1 -t UTF-8 < input.file > output.file
use autodie qw(:all);
open my $input, '<:encoding(Latin1)', $ARGV[0];
binmode STDOUT, ':encoding(UTF-8)';
use Encode qw(decode encode);
use autodie qw(:all);
open my $input, '<:raw', $ARGV[0];
binmode STDOUT, ':raw';
while (my $raw = <$input>) {
my $line = decode 'Latin1', $raw, Encode::FB_CROAK | Encode::LEAVE_SRC;
my $result = process($line);
print {STDOUT} encode 'UTF-8', $result, Encode::FB_CROAK | Encode::LEAVE_SRC;
}
关于perl - 在 Perl 中正确处理 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11792239/