【问题标题】:Encode a String to UTF-8 in Perl在 Perl 中将字符串编码为 UTF-8
【发布时间】:2020-11-29 08:55:20
【问题描述】:

utf8 库无法将我的数据转换为 utf-8。

#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use JSON;

my $data = qq( { "cat" : "Büster" } );
$data= utf8::encode($data);
$data= JSON::decode_json($data);
print $data->{"cat"};

输出:

malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)")

我不想使用 Unicode::UTF8 或编码。 我想使用 utf8 库来解决这个问题。

【问题讨论】:

  • 你的源文件的编码是什么?

标签: perl utf-8


【解决方案1】:

两个问题:

  • utf8::encode 就地编码;它不返回编码的字符串。
  • 您需要为您的终端适当地编码输出。
#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say );

# "Str of UCP" means "string of decoded text aka string of Unicode Code Points".
# "Str of UTF-8" means "string of text encoded using UTF-8 (bytes)".

use utf8;                                # Source code encoded using UTF-8
use open ':std', ':encoding(UTF-8)';     # Terminal provides/expects UTF-8

use JSON qw( decode_json );

my $json = qq( { "cat" : "Büster" } );   # Str of UCP because of "use utf8"

utf8::encode($json);                     # Str of UCP => Str of UTF-8
my $data = decode_json($json);           # Str of UTF-8 => Hash of str of UCP

say $data->{"cat"};                      # Expects str of UCP because of "use open :std"

或者,我们可以避免编码-解码往返,如下所示:

my $json = qq( { "cat" : "Büster" } );   # Str of UCP because of "use utf8"

my $decoder = JSON->new;
my $data = $decoder->decode($json);      # Str of UCP => Hash of str of UCP

say $data->{"cat"};                      # Expects str of UCP because of "use open :std"

【讨论】:

    【解决方案2】:

    要将字符串编码为 UTF-8 字节,可以使用 Encode 核心模块。

    我认为下面的代码可以像你想要的那样工作:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use utf8;
    use JSON::PP;
    use Encode;
    
    my $json = Encode::encode_utf8 q( { "cat" : "Büster" } );
    my $data= JSON::PP::decode_json($json);
    print Encode::encode_utf8  $data->{"cat"};
    

    我使用了JSON::PP 核心模块。您可以将其替换为JSON。它们是兼​​容的。

    【讨论】:

    • @ikegami 谢谢。我删除了有关使用 utf8 的评论。
    【解决方案3】:

    您需要 utf::encode,而不是解码。它们都改变了参数并且什么都不返回,因此将返回值分配给变量是没有意义的。

    #!/usr/bin/perl
    use strict;
    use warnings;
    use utf8;
    use JSON;
    
    my $data = qq({"cat":"Büster"});
    utf8::encode($data);
    $data = JSON::decode_json($data);
    binmode *STDOUT, ':encoding(UTF-8)';
    print $data->{cat};
    

    此外,输出文件句柄需要知道它应该使用什么编码,这就是 binmode 所做的。

    另外,请确保以 UTF-8 编码保存源代码。

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 2011-08-09
      • 2019-11-03
      • 2014-01-18
      • 2011-08-27
      • 2016-01-11
      • 2013-07-01
      • 2011-08-16
      相关资源
      最近更新 更多