I have the following perl code in where I have a perl structure as follows:
`
use Data::Dumper;
my %data = (
'status' => 200,
'message' => '',
'response' => {
'name' => 'John Smith',
'id' => '1abc579',
'ibge' => '3304557',
'uf' => 'XY',
'status' => bless( do{(my $o = 1)}, 'JSON::PP::Boolean' )
}
);
my $resp = $data{'status'};
print "Response is $resp n";
print Dumper(%data->{'response'});
Getting the status field works, however If I try something like this:
my $resp = $data{'response'}
I get Response is HASH(0x8b6640)
So I’m wondering if there’s a way I can extract all the data of the ‘response’ field on the same way I can do it for ‘status’ without getting that HASH…
I’ve tried all sort of combinations when accessing the data, however I’m still getting the HASH back when I try to get the content of ‘response’
2
Answers
Thanks for your posts. I fixed the code as follows:
Now it works like a charm, and I'm able to get the data I want.
$data{'response'}
is the correct way to access that field on a hash called%data
. It’s returning a hash reference, which prints out by default in the (relatively unhelpful)HASH(0x8b6640)
syntax you’ve seen. But if you pass that reference toDumper
, it’ll show you everything.to actually access those subfields, you need to dereference, which is done with an indirection
->
operation.The first access doesn’t need the
->
because you’re accessing a field on a hash variable (i.e. a variable with the%
sigil). The second one does because you’re dereferencing a reference, which, at least in spirit, has the$
sigil like other scalars.