nck
nck

Reputation: 2221

Storing "JSON to HASH" output in a variable makes Data::Dumper not work in perl

I´m getting an issue when trying to store a json comming from a String into a Hash. Take a look at this example:

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);
}

And the output is:

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

Does anyone understand why is this happening? Somehow the hash is there but Data::Dumper won´t take it?

Upvotes: 0

Views: 91

Answers (2)

ikegami
ikegami

Reputation: 385916

Precedence issue.

print Dumper \%hash . "\n";

means

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

but you want

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

The thing is, the value returned by Dumper will already end with a new line, so you really don't need another one. The following would do:

print(Dumper(\%hash));

If you want to omit the parens, there's no harm here.

print Dumper \%hash;

As for the prototype-related warning, you are getting it because a call to a sub with a prototype is encountered by the compiler before a declaration for that sub is encountered. In that situation, the call did not use the prototype, so Perl is letting you know this happened.

The simple solution is to just remove the useless prototype (the () in sub get_hash_from_json ()).

Upvotes: 3

simbabque
simbabque

Reputation: 54333

You are falling victim to precedence.

print Dumper \%hash1 . "\n";

The . concatenates \%hash1 and the newline, and that's what Dumper outputs. Put parentheses around it to make it work.

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

Or use say.

Upvotes: 3

Related Questions