Misfit
Misfit

Reputation: 72

Perl: hash from import JSON data, Dumper Outputs right data, However I can not access it

I have the following data in .json; actual values substituted.

{ "Mercury": [
        {
        "Long": "0.xxxxxx",
        "LongP": "0.xxxxx",
        "Eccent": "0.xxxx",
        "Semi": "0.xxxx",
        "Inclin": "0.xxxx",
        "ascnode": "0.xx.xxxx",
        "adia": "0.xxx",
        "visual": "-0.xx"
        }
]
}

This works fine:

my %data = ();

my $json        = JSON->new();
my $data        = $json->decode($json_text);

my $planet      = "Mercury";

print Dumper $data;    # prints:

This is all fine:

$VAR1 = {
          'Mercury' => [
                         {
                           'Inclin' => '7.',
                           'Semi' => '0.8',
                           'adia' => '6.7',
                           'LongP' => '77.29',
                           'visual' => '-0.00',
                           'Long' => '60.000',
                           'Eccent' => '0.0000',
                           'ascnode' => '48.0000'
                         }
                       ]
        };

However when I try to access the hash:

my $var = $data{$planet}{Long};

I get empty values, why?

Upvotes: 1

Views: 257

Answers (1)

ikegami
ikegami

Reputation: 385917

Problem 1

$data{$planet} accesses hash %data, but you populated scalar $data.

You want $data->{$planet} instead of $data{$planet}.

Always use use strict; use warnings;. It would have caught this error.


Problem 2

$data->{$planet} returns a reference to an array.

You want $data->{$planet}[0]{Long} (first element) or $data->{$planet}[-1]{Long} (last element) instead of $data->{$planet}{Long}. Maybe. An array suggests the number of elements isn't always going to be one, so you might want a loop.

Upvotes: 2

Related Questions