Jay Gridley
Jay Gridley

Reputation: 723

How to access data stored in 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?

Upvotes: 5

Views: 12549

Answers (5)

Anand Shah
Anand Shah

Reputation: 14913

Lots of ways, you can use a foreach loop

foreach my $key (%perl)
{
  print "$key is $perl{$key}\n";
}

or a while loop

while (my ($key, $value) = each %perl)
{
  print "$key is $perl{$key}\n";
}

Upvotes: -3

Eugene Yarmash
Eugene Yarmash

Reputation: 149853

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

Upvotes: 13

hobbs
hobbs

Reputation: 240020

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.

Upvotes: 5

Leon Timmermans
Leon Timmermans

Reputation: 30225

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.

Upvotes: 7

Pavunkumar
Pavunkumar

Reputation: 5335

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

Upvotes: -3

Related Questions