首页 > 解决方案 > 在变量中存储“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 不会接受它?

标签: jsonperlhash

解决方案


你正在成为优先权的牺牲品。

print Dumper \%hash1 . "\n";

.连接和换行符,这\%hash1就是Dumper输出。在它周围加上括号以使其工作。

print Dumper(\%hash1) . "\n";

或使用say.


推荐阅读