1

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!

1
  • The REF prints HASH so you know it is a reference to a hash. Commented Mar 3, 2015 at 13:23

1 Answer 1

1

$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

Sign up to request clarification or add additional context in comments.

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.