0

I've parsed JSON into the following data structure:

$VAR1 = {
          '041012020' => {
                            'item_number' => 'P2345'
                          },
          '041012021' => {
                            'item_number' => 'I0965'
                          },
          '041012022' => {
                            'item_number' => 'R2204'
                          }
        };

I'm trying to get the values of item_numbers using the following code, and it's giving me the HASH Values as output rather than the actual item_number values. Please guide me to get the expected values.

foreach my $value (values %{$json_obj}) {
       say "Value is: $value,";
 }

Output:

Value is: HASH(0x557ce4e2f3c0),
Value is: HASH(0x557ce4e4de18),
Value is: HASH(0x557ce4e4dcf8),

If I use the same code to get the keys it's working perfectly fine

foreach my $key (keys %{$json_obj}) {
        say "Key is: $key,";
 }

Output:

Key is: 041012020,
Key is: 041012020,
Key is: 041012022,
1
  • 3
    Your input is a Perl hash value. There is no JSON in this question. Commented Apr 14, 2021 at 21:45

2 Answers 2

3

The values of the hash elements are references to hashes ({ item_number => 'P2345' }). That's what you get when you stringify a reference. If you want the item number, you'll need to tell Perl that.

for my $value (values %$data) {
   say $value->{item_number};
}

or

for my $item_number ( map { $_->{item_number} } values %$data ) {
   say $item_number;
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for prompt response, when I use both of above snippets I'm getting `Use of uninitialized value in say at test.pl line 41. and Use of uninitialized value $item_number in say at test.pl line 45.
I changed misnamed $json_obj (which isn't JSON) to $data. Always use use strict; use warnings;
Thanks @Ikegami it's working as expected, I appreciate your help
Thanks, I thought to vote it so I did but checked the mark too.
0

Here is the short code for your question.

    #!usr/bin/perl
    
    $VAR1 = {
              '041012020' => {
                                'item_number' => 'P2345'
                              },
              '041012021' => {
                                'item_number' => 'I0965'
                              },
              '041012022' => {
                                'item_number' => 'R2204'
                              }
            };
            
    print "$VAR1->{$_}->{item_number}\n" for keys %$VAR1;

To use for in a block:

for my $key (keys %$VAR1) {
    print "$VAR1->{$key}->{item_number}\n"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.