perl - 转义多字节字符
问题描述
使用 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\
解决方案
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";
推荐阅读
- reactjs - 从异步箭头函数返回 JSX
- sql - 什么可以替换查询中的 IN 子句以使其更快?
- python - crontab 正在运行但未在 docker 上调度
- sql - SQL从3个值的计算中得到最小值
- html - 如何划分
分成多个部分? - python - 如何将中性情绪添加到经过训练的数据集中?使用 sklearn 和 nltk
- laravel - Laravel 7 迁移错误:外键约束形成错误
- python - Python/Pandas:将多个 CSV 文件转换为具有联合和有序标题并填充缺失的数据
- fortran - 当 fortran 代码读取 linux 集群上的文件时发生 SIGBUS
- amazon-s3 - Strapi 文件上传在生产中不起作用