tags:

views:

275

answers:

5

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?

A: 

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";
}
Anand
A: 

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

pavun_cool
+6  A: 

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";
} 
eugene y
+3  A: 

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.

Leon Timmermans
+2  A: 

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.

hobbs
OK, I figured out that print keys %{$perl} gets me key from Hash, but print values %{$perl} gets me another Hash reference. So I stored this reference in new scalar variable, but when I try to access data in this Hash, it gives me nothing.$json = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S"}}}';$coder = JSON::XS->new->utf8->pretty->allow_nonref;$perl = $coder->decode ($json);print keys %{$perl},"\n"; #give me glossaryprint values %{$perl},"\n"; #give me HASH(address)my $val = values %{$perl}; # store addressprint keys %{$val}; ##give nothing -- title expected
Jay Gridley