Reputation: 411
I have this code where array is an array of hashes:
my $hash = $array[0];
print "REF: " . ref($hash) . "\n";
my @names = keys ($hash);
The REF prints HASH so I know it is a hash.
But then the keys function returns an error:
Type of arg 1 to keys must be hash
How can I use the $hash as a hash?
Thanks!
Upvotes: 1
Views: 63
Reputation: 53478
$hash
isn't a hash, it's a hash reference. Therefore you need to dereference it before you can run keys on it.
Simplest way of doing this:
keys %$hash;
e.g.
foreach my $key ( keys %$hash ) {
print $key, " => ", $hash -> {$key},"\n";
}
And yes, I am mixing two dereference methods deliberately. The ->
notation says 'dereference this' - it's commonly used for object oriented stuff.
For more complex dereferencing %$hash{'key'}
is ambiguous, so you start needing brackets - %{$hash{'key'}}
for example.
See:
http://perldoc.perl.org/perlreftut.html
http://perldoc.perl.org/perlref.html
Upvotes: 1