perl - 在 Perl 中正确处理 UTF-8

标签 perl utf-8 character-encoding latin1

我得到了一个文件,(可能)以 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 introductionUnicode cookbook .

  • 最简单的 piconv :
    $ 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/

    相关文章:

    perl - 在 Perl 中通过 UDP 发送文件

    c++ - 如何在 C++ 控制台应用程序中执行 Perl 脚本?

    mysql - 如果我更改字符集,我可以使用 ' instead of ` 来分隔字段吗?

    python - Python,如何在输出中获得西里尔字母?

    c++ - 我可以使用 wstring 来读取、解析和发出 utf-8 吗?

    c++ - Python 到 C++ 字符编码

    java - Tomcat 9 中的编码问题 "The valid characters are defined in RFC 7230 and RFC 3986"

    单引号之间的 Perl 捕获

    c - 从网页内部链接获取值

    mysql - 将 MySQL ANSI 输入转换为 UTF-8