Home > Software design >  I can't print keys and values in Perl
I can't print keys and values in Perl

Time:07-12

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.

CodePudding user response:

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";
}

CodePudding user response:

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'ish representations) refer to the first hash in the array referenced by $name.
  • ${$name}[0]{'Key'}, $name->[0]->{'Key'}, etc. (equivalent'ish 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} ));
  •  Tags:  
  • perl
  • Related