json - 在变量中存储“JSON to HASH”输出会使 Data::Dumper 在 perl 中不起作用
问题描述
尝试将来自字符串的 json 存储到哈希中时遇到问题。看看这个例子:
use strict;
use warnings;
use utf8;
use JSON;
use Data::Dumper;
my %hash1 = %{get_hash_from_json()};
print "Final Dump:\n";
print Dumper \%hash1 . "\n";
print "Keys:\n";
for (keys %hash1) {printf "key is $_\n";}
sub get_hash_from_json (){
my $json = '{"hello": "world", "hello2": "world"}';
print "Dumper without variable:\n";
print Dumper (from_json($json)) . "\n";
print "Dumper with variable:\n";
my $hash_ref = from_json($json);
my %hash = %{$hash_ref};
print Dumper \%hash . "\n";
return from_json($json);
}
输出是:
main::get_hash_from_json() called too early to check prototype at example.pl line 10.
Dumper without variable:
$VAR1 = {
'hello' => 'world',
'hello2' => 'world'
};
Dumper with variable:
$VAR1 = 'HASH(0x29c88e0)
';
Final Dump:
$VAR1 = 'HASH(0x2512438)
';
Keys:
key is hello2
key is hello
有谁明白为什么会这样?不知何故,哈希在那里,但 Data::Dumper 不会接受它?
解决方案
你正在成为优先权的牺牲品。
print Dumper \%hash1 . "\n";
.
连接和换行符,这\%hash1
就是Dumper
输出。在它周围加上括号以使其工作。
print Dumper(\%hash1) . "\n";
或使用say
.
推荐阅读
- python - SciPy:为具有对数频率标度的音频制作频谱图并从中恢复原始信号
- .net - .NET 如何在 OIDC 中间件中访问 DBContext
- javascript - setInterval 和 clearInterval 问题?
- python - 运行其他外部 python 脚本时缺少 numpy
- javascript - JavaScript / JQuery 无效的 EWS SOAP XML 响应
- java - java.lang.NullPoinerException 错误。如何将字符串转换为 WebElement (java)
- docker - Fetch 模块在 Docker 中运行时返回“无法计算远程文件的校验和”,但在不在 Docker 中时工作正常
- c - 了解工作队列中的快速更新
- python - SQL 包含 0 个参数标记,但提供了 1 个参数','HY000'
- google-sheets - 用“MONTH(“Oct”&1)”计算当前月份不能正常工作