I have this code:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
%perl = $coder->decode ($json);
When I write print %perl
variable it says HASH(0x9e04db0). How can I access data in this HASH?
I have this code:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
%perl = $coder->decode ($json);
When I write print %perl
variable it says HASH(0x9e04db0). How can I access data in this HASH?
Lots of ways, you can use a foreach loop
foreach $key (%perl)
{
print "$key is $perl{$key}\n";
}
or a while loop
while (($key, $value) = each %perl)
{
print "$key is $perl{$key}\n";
}
You need to specify the particular key of hash, Then only you will be able to access the data from the hash .
For example if %perl hash has key called 'file' ;
You suppose to access like below
print $perl{'file'} ; # it would print the file key value of the %perl hash
As the decode
method actually returns a reference to hash, the proper way to assign would be:
%perl = %{ $coder->decode ($json) };
That said, to get the data from the hash, you can use the each builtin or loop over its keys and retrieve the values by subscripting.
while (my ($key, $value) = each %perl) {
print "$key = $value\n";
}
for my $key (keys %perl) {
print "$key = $perl{$key}\n";
}
JSON::XS->decode returns a reference to an array or a hash. To do what you are trying to do you would have to do this:
$coder = JSON::XS->new->utf8->pretty->allow_nonref;
$perl = $coder->decode ($json);
print %{$perl};
In other words, you'll have to dereference the hash when using it.
The return value of decode
isn't a hash and you shouldn't be assigning it to a %hash
-- when you do, you destroy its value. It's a hash reference and should be assigned to a scalar. Read perlreftut.