Reputation: 191
I have a hash of hashes, $json, received by a perl script from a post method. After decoding the structure with JSON,
use JSON;
my $decode = decode_json($json);
here is the structure from Data::Dumper:
$VAR1 = {
'11' => {
'_by' => 122,
'_bx' => 296,
'_ay' => 115,
'_ax' => 337
},
'21' => {
'_by' => 138,
'_bx' => 395,
'_ay' => 135,
'_ax' => 394
},
'7' => {
'_by' => 87,
'_bx' => 392,
'_ay' => 82,
'_ax' => 389
},
'17' => {
'_by' => 132,
'_bx' => 392,
'_ay' => 129,
'_ax' => 385
},
'2' => {
'_by' => 80,
'_bx' => 266,
'_ay' => 87,
'_ax' => 222
},
'22' => {
'_by' => 138,
'_bx' => 395,
'_ay' => 138,
'_ax' => 395
},
'1' => {
'_by' => 87,
'_bx' => 222,
'_ay' => 94,
'_ax' => 196
}
};
Keys actually go from 0 to 25 (I shorten the structure here for the sake of brevity)
I'm wondering why the following code returns an error:
for (my $i=0; $i<=25; $i++) {
print $decode{$i}{'_bx'};
}
Upvotes: 3
Views: 196
Reputation: 66957
What you've got is a reference to a hash, not a hash, so you need to dereference it. You can access single elements using the ->
operator.
for (my $i=0; $i<=25; $i++) {
print $decode->{$i}{'_bx'};
}
Or much prettier:
for my $i ( 0..25 ) {
print $decode->{$i}{_bx};
}
If you want to dereference the entire hash at once, you can use
my %new = %$decode;
for my $i ( 0..25 ) {
print $new{$i}{_bx};
}
For more:
Upvotes: 5