【问题标题】:How do print a sequence of characters (hex) as UTF8 characters in Perl?如何在 Perl 中将字符序列(十六进制)打印为 UTF8 字符?
【发布时间】:2019-03-21 19:20:49
【问题描述】:

我在 Perl 中有一个变量,它只是一个字母和数字序列:

my $var = "48656c6c6f20576f726c64";

序列代表字符串Hello World

即可以将其视为0x48 0x65 0x6c 0x6c 0x6f 0x20 0x57 0x6f 0x72 0x6c 0x64Hello World 的十六进制表示。

如何将$var 打印为可读的 UTF8?

简短:如何打印Hello World

【问题讨论】:

    标签: perl utf-8 hex


    【解决方案1】:

    pack

    print pack("H*", $var);
    

    或者如果数据在解码后确实是 UTF-8 编码

    use Encode;
    print Encode::decode("UTF-8", pack("H*", $var));
    

    【讨论】:

    • 感谢(最快)回答!完美运行!对于阅读本文的任何人,我还添加了binmode STDOUT, ":utf8";。我有一些“宽”字
    • @user2426316,你永远不应该使用:utf8binmode STDOUT, ":utf8"; 应该是 binmode STDOUT, ":encoding(UTF-8)";,你也应该对 STDIN 和 STDERR 做同样的事情。 use open ':std', ':encoding(UTF-8)'; 做了所有这些。
    【解决方案2】:

    获取文本:

    use Encode qw( decode_utf8 );
    
    my $hex   = "48656c6c6f20576f726c64";
    my $bytes = pack('H*', $hex);
    my $text  = decode_utf8($bytes);
    

    要打印它:

    use feature qw( say );
    use open ':std', ':encoding(UTF-8)';
    
    say $text;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2015-12-16
      • 2014-06-24
      • 1970-01-01
      相关资源
      最近更新 更多