gpt4 book ai didi

perl - 当我使用 JSON::decode_json 时,Test::Deep::cmp_deeply 中 unicode 字符串的比较失败

转载 作者:行者123 更新时间:2023-12-02 05:53:49 25 4
gpt4 key购买 nike

在 Perl v5.10.1 中,我需要将带有 unicode 字符的 native Perl 结构与 JSON::decode_json 创建的类似结构进行比较。

示例:

use strict; use warnings;
#use utf8;
use JSON;
use Test::Deep qw(cmp_deeply);
cmp_deeply(["1"], JSON::decode_json('["1"]'), 'utf8 test 11'); # will pass
cmp_deeply(["≥"], JSON::decode_json('["1"]'), 'utf8 test ≥1'); # will fail
cmp_deeply(["1"], JSON::decode_json('["≥"]'), 'utf8 test 1≥'); # will fail
cmp_deeply(["≥"], JSON::decode_json('["≥"]'), 'utf8 test ≥≥'); # should pass

我无法解释最后一个案例发生了什么,为什么这两个结构不相等?我尝试过了 R T F M这并没有真正提高我对这个问题的理解。

这是输出(由于 TAP 太冗长而稍作编辑):

ok 1 - utf8 test 11
not ok 2 - utf8 test ≥1
# Compared $data->[0]
# got : '≥'
# expect : '1'
not ok 3 - utf8 test 1≥
Wide character in print at Test/Builder.pm line 1698.
# Compared $data->[0]
# got : '1'
# expect : '≥'
not ok 4 - utf8 test ≥≥
Wide character in print at Test/Builder.pm line 1698.
# Compared $data->[0]
# got : 'â¥'
# expect : '≥'
<小时/>

当我使用 use utf8; 尝试时,情况更糟(脚本在第二次测试后死亡):

ok 1 - utf8 test 11
not ok 2 - utf8 test ≥1
Wide character in print at Test/Builder.pm line 1698.
Wide character in print at Test/Builder.pm line 1698.
Wide character in print at Test/Builder.pm line 1698.
# Compared $data->[0]
# got : '≥'
# expect : '1'
Wide character in subroutine entry at ...
# Tests were run but no plan was declared and done_testing() was not seen.

我还尝试了一种适用于比较的解决方法..

use utf8;
cmp_deeply(["≥"], JSON->new->utf8(0)->decode('["≥"]'), 'utf8 test ≥≥');

...但我仍然收到愚蠢的警告:

ok 1 - utf8 test ≥≥
Wide character in print at Test/Builder.pm line 1698.

有没有办法让它工作 - 比如 use magic_unicode_solution;

或者也许我应该以不同的方式进行测试以使其与 Unicode 兼容?

最佳答案

此测试将通过:

use Encode;
cmp_deeply( [ Encode::decode("utf8","≥") ],
JSON::decode_json('["≥"]'), 'utf8 test ≥≥');

JSON 解码器将输入视为 UTF-8 编码并返回解码后的字符串。您的原始测试(测试 4)将 UTF-8 编码的字符串(两个八位字节)与解码的字符串(单个宽字符)进行比较。

关于perl - 当我使用 JSON::decode_json 时,Test::Deep::cmp_deeply 中 unicode 字符串的比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043579/

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