gpt4 book ai didi

Perl UTF8 到 UTF16 的转换错误 - 宽字符

转载 作者:行者123 更新时间:2023-12-02 05:08:50 24 4
gpt4 key购买 nike

有人能告诉我为什么这段代码会失败并出现以下错误吗?我也试过 utf8::downgrade() 在调用 from_to() 之前没有成功。使用 Perl 5.14.2。

有什么想法吗??

代码:

use Encode qw(from_to);
use HTML::Entities;

$s = "มหั&#3624";
$foo = decode_entities($s);
print "is foo UTF8? ", utf8::is_utf8($foo), "\n";
from_to($foo, 'UTF-8', 'UTF-16');

输出:

is foo UTF8? 1
Cannot decode string with wide characters at /usr/lib/perl/5.14/Encode.pm line 194.

最佳答案

首先,utf8::is_utf8 并不像您认为的那样。它提供了有关字符串内部存储的详细信息,nothing you should ever need to check .

问题是您的字符串未使用 UTF-8 编码。它根本没有编码。 decode_entities 接受并返回解码后的字符串,即 Unicode 代码点的字符串。

你可以使用

encode('UTF-16', decode_entities(decode('UTF-8', $foo)))

关于Perl UTF8 到 UTF16 的转换错误 - 宽字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15839355/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com