skip to Main Content

I have the following perl code in where I have a perl structure as follows:
`

use Data::Dumper;

my %data = (
  'status' => 200,
  'message' => '',
  'response' => {
    'name' => 'John Smith',
    'id' => '1abc579',
    'ibge' => '3304557',
    'uf' => 'XY',
    'status' => bless( do{(my $o = 1)}, 'JSON::PP::Boolean' )
  }

);

my $resp = $data{'status'};
print "Response is $resp n";
print Dumper(%data->{'response'});

Getting the status field works, however If I try something like this:
my $resp = $data{'response'}

I get Response is HASH(0x8b6640)

So I’m wondering if there’s a way I can extract all the data of the ‘response’ field on the same way I can do it for ‘status’ without getting that HASH…

I’ve tried all sort of combinations when accessing the data, however I’m still getting the HASH back when I try to get the content of ‘response’

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for your posts. I fixed the code as follows:

    use Data::Dumper;
    
    my %data = (
      'status' => 200,
      'message' => '',
      'response' => {
        'name' => 'John Smith',
        'id' => '1abc579',
        'ibge' => '3304557',
        'uf' => 'XY',
        'status' => bless( do{(my $o = 1)}, 'JSON::PP::Boolean' )
      }
    
    );
    
    my $resp = $data{'response'};
    print Dumper($resp);
    

    Now it works like a charm, and I'm able to get the data I want.


  2. $data{'response'} is the correct way to access that field on a hash called %data. It’s returning a hash reference, which prints out by default in the (relatively unhelpful) HASH(0x8b6640) syntax you’ve seen. But if you pass that reference to Dumper, it’ll show you everything.

    print Dumper($data{'response'});
    

    to actually access those subfields, you need to dereference, which is done with an indirection -> operation.

    print $data{'response'}->{'name'}
    

    The first access doesn’t need the -> because you’re accessing a field on a hash variable (i.e. a variable with the % sigil). The second one does because you’re dereferencing a reference, which, at least in spirit, has the $ sigil like other scalars.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search