Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am new to perl.I have a text file.I want to read it into hash and array.Please help

{ "InstanceStatuses": [ { "InstanceId": "i-308c0b3c", "InstanceState": { "Code": 16, "Name": "running" }, "AvailabilityZone": "us-west-2b", "SystemStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] }, "InstanceStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] } } ] }

Replies are listed 'Best First'.
Re: reading a text file into hash
by pme (Monsignor) on Jun 30, 2015 at 08:23 UTC
    Hi AM,

    This text looks like JSON (http://json.org). JSON can be easily processed by JSON or JSON::XS modules.

    use strict; use warnings; use Data::Dumper; use JSON; my $json_text = q{ { "InstanceStatuses": [ { "InstanceId": "i-308c0b3c", "InstanceState": { "Code": 16, "Name": "running" }, "AvailabilityZone": "us-west-2b", "SystemStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] }, "InstanceStatus": { "Status": "ok", "Details": [ { "Status": "passed", "Name": "reachability" } ] } } ] } }; # decode JSON text my $hashref = decode_json $json_text; # dump the hashref print Dumper( $hashref ) . "\n"; # access Name print "Name: '$hashref->{InstanceStatuses}->[0]->{InstanceState}->{Nam +e}'\n";

      Hi pme, Thanks a lot for your help.

Re: reading a text file into hash
by ww (Archbishop) on Jun 30, 2015 at 18:04 UTC

    I want a pony!

      But you want me to muck out your stable?

    Pls read PerlMonks FAQ. This is a place where you can get a lot of help learning, if you care to try, but it's not code-a-matic where you put in a request and the Monks do your work for you.


    Questions containing the words "doesn't work" (or their moral equivalent) will usually get a downvote from me unless accompanied by:
    1. code
    2. verbatim error and/or warning messages
    3. a coherent explanation of what "doesn't work actually means.
Re: reading a text file into hash
by Anonymous Monk on Jun 30, 2015 at 07:57 UTC

    I want to retrieve "Name":"running" line out of it.Please help.

Re: reading a text file into hash
by Anonymous Monk on Jun 30, 2015 at 08:37 UTC

    Thanks a lot.It is working fine.But I need to read that json input from a file.I can't hard code that into the code.Please help with that

      Please read the relevant part of the docs you have been addressed to.

      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.