BioRod
BioRod

Reputation: 549

I can't print keys and values in Perl

I have a data structure that I got from this code.

my $name = $data->{Instances}->[0]->{Tags};

That data structure looks like this

$VAR1 = [
      {
        'Key' => 'Name',
        'Value' => 'fl-demo'
      },
      {
        'Value' => 'FL',
        'Key' => 'state'
      }
    ];

I'm trying to print the keys and values with this

foreach my $key (sort keys %$name) {
my $value = $name->{$key};
print "$key  => $value\n";
}

I'm getting

Not a HASH reference at ./x.pl line 19.

Upvotes: 0

Views: 94

Answers (3)

ahi324
ahi324

Reputation: 439

Elaborating on a previous answer:

  • $name is a reference to an array containing references to hashes.
  • @$name and @{$name} (equivalent representations) refer to the array that $name references.
  • ${$name}[0] and $name->[0] (equivalent representations) refer to the first hash in the array referenced by $name.
  • ${$name}[0]{'Key'}, $name->[0]->{'Key'}, etc. (equivalent representations) refer to 'Key''s hash value in the first hash in the array referenced by $name.

As such, the following would iterate over all array and hash elements:

foreach my $hashref ( @{$name} )
{
    foreach my $key ( sort(keys(%{$hashref})) )
    {
        printf("%s => %s\n",$key,$hashref->{$key});
    }
    print "\n";
}

Or, more compactly (and arguably unreadably):

printf("%s\n",join("\n", map {
    my $h = $_;
    join(', ', map { sprintf('%s=%s',$_,$h->{$_}) } sort(keys(%{$h})) );
} @{$name} ));

Upvotes: 1

Polar Bear
Polar Bear

Reputation: 6808

The data structure dump of variable $name indicates that you have array reference.

You can use loop to output the data of interest, do not forget to dereference $name variable.

use strict;
use warnings;
use feature 'say';

my $name = [
        {
            'Key' => 'Name',
            'Value' => 'fl-demo'
        },
        {
            'Value' => 'FL',
            'Key' => 'state'
        }
    ];
    

say "$_->{Key} = $_->{Value}" for @$name;

Output

Name = fl-demo
state = FL

Upvotes: 1

Erwin
Erwin

Reputation: 952

The tags are returned as an array, not a hash. So you're looking at doing something like this, instead, to iterate over them:

foreach my $tag (@$name) {
    my $key = $tag->{Key};
    my $val = $tag->{Value};
    print "$key => $val\n";
}

Upvotes: 1

Related Questions