I have a Perl class that contains a hash instance variable for storing other objects. I would like to have a method to print the number of elements in the hash but I am getting the following error message on the line return keys($self->{'_things'});
Type of arg 1 to keys must be hash (not hash element)
package MyClass;
use strict;
sub new {
my ($class) = @_;
my $self = {
_things => undef
};
$self->{'_things'} = ();
bless $self, $class;
return $self;
}
sub get_count {
my ( $self ) = @_;
return keys($self->{'_things'});
}
Use
$self->{'_things'}is just a reference to a hash, andkeys()expects a hash as its argument—so, you have to dereference it first by wrapping it in%{…}. Finally, since you want to count items, you have to make sure the return value ofkeys()(which is a list) is interpreted in scalar context, by wrapping it inscalar(…).