Search code examples
perlhashdereference

Hash dereference in Perl


I have a HASH reference $job which has this data:

{
    "opstat"  : "ok",
    "response": {
                "group_id":23015,
                "order_id":"139370",
                "job_count":"10",
                "credits_used":"100.45",
                "currency":"USD"
                }
}

I want to print the hash value of "response" key. I tried doing this but did not work

print %{$job->{'response'}}

Edit

I do not want any formatting. I want to know how to access each element in the value of 'response' key.


Solution

  • I want to know how to access each element in the value of 'response' key.

    By definition, you need some kind of loop. A foreach loop is typical, although you could also use map.

    for my $key (keys %{$job->{response}}) {
       my  $val = $job->{response}{$key};
       print("$key: $val\n");  # Or whatever
    }
    

    or

    my $response = $job->{response};
    for my $key (keys %$response) {
       my  $val = $response->{$key};
       print("$key: $val\n");  # Or whatever
    }