Search code examples
jsonperlhashref

Extracting values from hash created by perl JSON::Syck::Load


I've got a very simple Perl issue that I can't for the life of me figure out.

I'm consuming JSON formatted data from a REST endpoint in a perl script. The data is shaped like this:

{
   "ScriptRunning": true
}

There's some other stuff, but really all I care about is the ScriptRunning tag. I'm consuming this data using JSON::Syck::Load like so:

my $running_scripts = JSON::Syck::Load($output_from_rest_call)

(in my current environment it is not possible to get other libraries for CPAN, so I'm stuck with that). All that is working correctly as far as I can tell, I used Data::Dumper to confirm the data looks good:

$VAR1 = {
    'ScriptRunning' => 1 # or '' if false
}

However, I can't figure out how to actually get the value of 'ScriptRunning'. I've done print ref $running_scripts and confirmed that it is a HASH, however when I try to index into the hash I'm not getting anything. I've tried the following:

my $script_is_running = $running_scripts{'ScriptRunning'};
my $script_is_running = $running_scripts{ScriptRunning};
my $keys_in_running_scripts = keys $running_scripts; # keys_in_running_scripts is empty
my $keys_in_running_scripts = keys %running_scripts; # keys_in_running_scripts is empty

Any ideas?


Solution

  • You need to use strict; (and use warnings; while you are at it, maybe use diagnostics; too, when you are really stuck). As a general rule, ALWAYS use strict; and use warnings; because they prevent problematic code from running and give you some much more helpful output.

    You should also read perldoc perlreftut, which helps explain what you are dealing with.

    Your variable $running_scripts is not a hash, but a "hash reference", which is an important distinction. When you call ref on a real hash, it returns a false value, since it is not a reference.

    What you need to do is "dereference" using the arrow operator to get the value.

    To get the keys call to work, there's a separate syntax for dereferencing.

    my $script_is_running = $running_scripts->{ScriptRunning};
    my @keys_in_running_scripts = keys %{$running_scripts};