【问题标题】:In Perl, how can I convert an array of bytes to a Unicode string?在 Perl 中,如何将字节数组转换为 Unicode 字符串?
【发布时间】:2015-05-01 12:49:04
【问题描述】:

有人知道怎么做吗?这甚至可能吗?

我已经阅读了有关解码和编码的信息,但由于我不是专家,我不知道它是否会有所帮助。

【问题讨论】:

    标签: arrays perl utf-8 bytearray


    【解决方案1】:

    当然,这是可能的。如果你有字节数组

    my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
    

    您需要先将它们组合成一串八位字节:

    my $x = join '', map chr, @bytes;
    

    然后,您可以使用 utf8::decode 将其转换为 UTF-8 就地

    utf8::decode($x)
        or die "Failed to decode UTF-8";
    

    您也可以使用Encode::decode_utf8

    #!/usr/bin/env perl
    
    use 5.020; # why not?!
    use strict;
    use warnings;
    
    use Encode qw( decode_utf8 );
    use open qw(:std :utf8);
    
    my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
    my $x = join '', map chr, @bytes;
    
    say "Using Encode::decode_utf8";
    say decode_utf8($x);
    
    utf8::decode($x)
        or die "Failed to decode in place";
    
    say "Using utf8::decode";
    say $x;
    

    输出:

    C:\Temp> perl tt.pl
    使用编码::decode_utf8
    αβγ
    使用 utf8::decode
    αβγ

    Encode 允许您在多种字符编码之间进行转换。它的功能允许您指定在encoding/decoding operations fail 的情况下会发生什么,而使用utf8::decode 您仅限于显式检查成功/失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2017-04-16
      • 2013-02-05
      • 2017-02-19
      相关资源
      最近更新 更多