How to access data stored in Hash
I have t开发者_运维百科his 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?
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.
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
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";
}
精彩评论