gpt4 book ai didi

perl - 在 Perl 中,如何区分 JSON 编码中的数字和字符串哈希值?

转载 作者:行者123 更新时间:2023-12-04 22:28:20 25 4
gpt4 key购买 nike

在下面的代码中,我有一个与哈希绑定(bind)的类。在 FETCH函数,我正在打印 JSON key 编码:

package Example::Tie;
use JSON;
my $json = JSON->new();

sub TIEHASH {
my ($pkg,@list) = @_;
bless { @list }, $pkg;
}

sub FETCH {
my ($tied,$key) = @_;
return $json->encode({key => $key});
}

package Example;

sub new {
my ($pkg,@list) = @_;
my $self = {};
tie %$self, 'Example::Tie', @list;
bless $self, $pkg;
}

package main;
my $exp = Example->new();
print($exp->{0} . "\n");

我得到以下输出:
{"key":"0"}

这导致 0被编码为字符串。有没有办法将其编码为数字?
print($exp->{0} . "\n"); # this should print {"key":0}
print($exp->{'0'} . "\n"); # this should print {"key":"0"}

最佳答案

由于 Perl 中没有字符串或数字的真正概念,而只有标量,所以这很棘手。 JSON module tries通过查看使用它编码的值的最后一个上下文来做到这一点。

Simple Perl scalars (any scalar that is not a reference) are the most difficult objects to encode: this module will encode undefined scalars as JSON null values, scalars that have last been used in a string context before encoding as JSON strings, and anything else as number value:

# dump as number
encode_json [2] # yields [2]
encode_json [-3.0e17] # yields [-3e+17]
my $value = 5; encode_json [$value] # yields [5]

# used as string, so dump as string
print $value;
encode_json [$value] # yields ["5"]

# undef becomes null
encode_json [undef] # yields [null]


您在 FETCH 中的代码没有专门这样做。所以它必须在其他地方。

我的猜测是 Perl 对哈希键的自动引用是这里的罪魁祸首。
$exp->{0}; # this should print {"key":0}
$exp->{'0'}; # this should print {"key":"0"}

这两个表达式是等价的。 Perl 会自动处理 {} 中的内容。对于引用的哈希(ref)元素,它们成为字符串。因为这很容易忘记, there is best practice始终使用单引号 '' .

Perldata says (强调我的):

Hashes are unordered collections of scalar values indexed by their associated string key.



这个想法是哈希没有数字键。如果有数字键,它们可以排序,然后你有一个数组。

您可以调用 FETCH 获得进一步的证明。直接使用不带引号的数字作为参数。
Example::Tie->FETCH(1);

这将导致
{"key":1}

因此,我得出结论,使用 tie使用 JSON 模块,您想要做的事情是不可能的,除非您明确尝试将其强制返回为数字。 JSON 模块的文档中有一个示例。

You can force the type to be a number by numifying it:

my $x = "3"; # some variable containing a string
$x += 0; # numify it, ensuring it will be dumped as a number
$x *= 1; # same thing, the choice is yours.

关于perl - 在 Perl 中,如何区分 JSON 编码中的数字和字符串哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45463118/

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