我有一个Perl类,它包含一个用于存储其他对象的哈希实例变量。我想有一个方法来打印哈希中的元素数量,但我在行return keys($self->{'_things'});
上收到以下错误消息
arg 1到键的类型必须是哈希(不是哈希元素)
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'});
}
答案 0 :(得分:4)
使用
return scalar(keys(%{$self->{'_things'}}));
$self->{'_things'}
只是哈希的引用,而keys()
期望哈希作为其参数 - 因此,您必须首先通过将其包装在{{{{{ 1}}。最后,由于您要计算项目,因此必须确保%{…}
(列表)的返回值在标量上下文中解释,方法是将其包装在keys()
中。
答案 1 :(得分:2)
如果我理解正确,$self->{_things}
应包含哈希数据结构。如果是这样,您有两个问题:
sub new {
my ($class) = @_;
my $self = {
# Initialize _things to be a reference to an empty hash.
_things => {},
};
bless $self, $class;
return $self;
}
sub get_count {
my ( $self ) = @_;
# Here's the way to get the N of keys.
# The %{ FOO } syntax will take a hash reference (FOO in this case) and
# convert it to a hash, on which we can then call keys().
return scalar keys %{ $self->{'_things'} };
}
答案 2 :(得分:0)
错误信息完全正确! ;)您需要将元素“取消引用”为哈希值,您还需要在标量上下文中调用keys()来获取计数。
$ perl -wle 'use strict; my $href = { foo => undef }; $href->{foo} = (); print sclar keys $href->{foo}'
Type of arg 1 to keys must be hash (not hash element) at -e line 1, at EOF
Execution of -e aborted due to compilation errors.
VS
$ perl -wle 'use strict; my $href = { foo => undef }; $href->{foo} = (); print scalar keys %{ $href->{foo} }'
0
您可能希望使用哈希引用替代$ self-> {_ things}以避免意外列表展平和其他问题。
$ perl -wle 'use strict; my $href = { foo => undef }; $href->{foo} = { bar => 1 }; print scalar keys %{ $href->{foo} };'
1