【发布时间】:2017-01-13 13:29:22
【问题描述】:
更新:全新安装没有问题。我放弃了尝试修复升级后的 Ubuntu。
原始问题:
我正在使用 perl CPAN 包 JSON 使用 to_json 函数将 hasref 转换为 json。
这在带有 perl 版本 5.18.2 的 Ubuntu 14.04 上运行良好,但在升级到带有 perl 版本 5.22.1 的 Ubuntu 16.04 后,我收到错误消息:
hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)
原来的代码是这样的:
my $lang = {
'connection_lost' => 'Network connection was lost',
'connection_lost_more' => 'Please refresh this page to fix this problem'
};
my $json_lang = to_json($lang);
我用warn ref($lang)检查了$lang的类型,它返回了'HASH',所以它应该是一个hashref?
我试着把它改成这样:
my %lang;
$lang{'connection_lost'} = 'Network connection was lost';
$lang{'connection_lost_more'} = 'Please refresh this page to fix this problem';
my $json_lang = to_json(%lang);
还有这个:
my %lang;
$lang{'connection_lost'} = 'Network connection was lost';
$lang{'connection_lost_more'} = 'Please refresh this page to fix this problem';
my $json_lang = to_json(\%lang);
两者都失败了。
然后我尝试了allow_nonref 开关:
my $lang = {
'connection_lost' => 'Network connection was lost',
'connection_lost_more' => 'Please refresh this page to fix this problem'
};
my $jsonnonref = JSON->new->allow_nonref;
my $json_lang = $jsonnonref->to_json($lang);
导致错误消息to_json should not be called as a method
如何让它工作?
对我不起作用的绝对最小代码:
package Handlers::test_handlers;
use strict;
use warnings;
use Apache2::Const -compile => qw(OK);
use Apache2::Request;
use JSON;
sub handler {
my $lang = {
'connection_lost' => 'connection_lost',
'connection_lost_more' => 'connection_lost_more'
};
#my $json_lang = 'Hello world';
my $json_lang = to_json($lang);
print $json_lang;
return Apache2::Const::OK;
}
1;
使用“Hello world”行有效,而 to_json 行不行。
【问题讨论】:
-
我刚刚在 Xenial 上的 Perl 5.22 上尝试了您的原始代码,它运行良好。我认为您需要向我们展示更多您的代码。
-
我认为在某个时间点,
JSON切换到使用JSON::XS或JSON::PP(按优先顺序排列)。也许当这种情况发生时,它的语义发生了轻微的变化。 -
我在最后添加了一个
handler();行并安装了 libapache2-request-perl 和 libapache2-mod-perl2,它工作正常。您是否使用系统 Perl 和模块或类似 Perlbrew 来管理环境? -
除了 libapache2-request-perl 和 libapache2-mod-perl2 我没有安装任何自定义 perl 包。 JSON 是通过 CPAN 安装的
-
请提供
perl -E'use JSON; eval { require JSON::XS }; eval { require JSON::PP }; say "<$_>" for $JSON::VERSION, $JSON::XS::VERSION, $JSON::PP::VERSION, $INC{"JSON.pm"}, JSON->backend, to_json({a=>"b",c=>"d"})'的输出