【问题标题】:Escape multibyte characters转义多字节字符
【发布时间】:2019-04-12 03:24:02
【问题描述】:

使用 Python - 我可以获取一个字符串并使用多字节字符返回它 UTF-8 转义:

$ python3 -c 'print("hello ☺ world".encode("utf-8"))'
b'hello \xe2\x98\xba world'

或 unicode 转义:

$ python3 -c 'print("hello ☺ world".encode("unicode-escape"))'
b'hello \\u263a world'

Perl 可以做这样的事情吗?我试过“quotemeta”,但似乎不是 正确的工具:

$ perl -e 'print quotemeta("hello ☺ world\n");'
hello\ \�\�\�\ world\

【问题讨论】:

  • 仅供参考,您需要 -Mutf8use utf8; 才能从 UTF-8 解释源代码(因为这就是 Perl 最终从命令行或文件接收它的方式)。这与您最终输出它的方式无关。
  • @Lankymart 不是重复的。链接的问题是关于正确输出 Unicode 字符。这个问题是关于转义 Unicode 字符的。解决方案(IO 层与 Data::Dumper)完全不同。
  • @amon 我可能不是 Perl 程序员,但是使用 print 输出多字节字符似乎是一样的,但是你旋转它。
  • @Lankymart 我是一个 Perl 标记金徽章持有者,如果它是重复的,可以通过单次投票来重复关闭问题。但是这里不需要理解 Perl。该问题询问如何输出正确编码的 Unicode 字符,例如????。这个问题还想输出转义,例如\x{1f600}。他们都使用print,只是因为他们都想输出一些东西,但他们输出的东西不同。

标签: perl unicode utf-8 escaping unicode-escapes


【解决方案1】:

Data::Dumper,一方面,可以做到这一点。

use utf8;
use Encode;
use Data::Dumper;
$Data::Dumper::Terse = 1;   # suppress  '$VAR1 = ...' header
$Data::Dumper::Useqq = 1;   # make output printable

print Dumper("hello ☺ world");
print Dumper(encode("UTF-8","hello ☺ world"));

输出:

"hello \x{263a} world"
"hello \342\230\272 world"

更新Data::Dumper模块中的相关函数为qquote,所以可以跳过设置$Useqq$Terse

use utf8;
use Encode;
use Data::Dumper;

print Data::Dumper::qquote("hello ☺ world"), "\n";
print Data::Dumper::qquote(encode("UTF-8","hello ☺ world")), "\n";

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多