首页 > 解决方案 > 转义多字节字符

问题描述

使用 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\

标签: perlunicodeutf-8escapingunicode-escapes

解决方案


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";

推荐阅读