【发布时间】:2021-04-30 15:59:01
【问题描述】:
我有一堂课:
sub new {
my ($class, $name) = @_;
my $self = {
_ids => [],
_devices => {}
};
bless ($self, $class);
return $self;
}
我将一个数组传递给子程序,然后说:
sub Importids {
my ($self, $id_ref) = @_;
foreach $id (@{$id_ref})
{
push(@{$self->{_ids}}, $id);
}
}
我还想在这个函数中添加我初始化哈希的功能,但是我在做这件事时很费劲。 最后,我希望我的哈希对于多个 id 看起来像这样:
_device --> id1|
--> status --> 0/1
id2|
--> status --> 0/1
其中 id 是键。
我尝试在函数中这样做:
sub Importids {
my ($self, $id_ref) = @_;
foreach $id (@{$id_ref})
{
push(@{$self->{_ids}}, $id);
}
foreach my $id_value(@{$self->{_ids}})
{
$self->{_devices}{$id_value}{'status'} = 0;
}
}
但是当我去检查如下内容时,它只返回哈希的十六进制转储
for my $hash_key (keys %{$self->{_devices}})
{
print $self->{_devices}{$hash_key};
#print keys % {$self->_devices}};
}
给予:
HASH(0x....)
HASH(0x....)
...
...
HASH(0x....)
但是,当我尝试时:
for my $hash_key (keys %{$self->{_devices}})
{
print $self->{_devices}->{$hash_key}->{'status'};
}
我得到了我想要的:
0
0
...
0
我应该如何访问密钥并添加额外的字段,例如 status2''?
【问题讨论】:
-
这里
print $self->{_devices}{$hash_key};你正在打印 hashref。这里$self->{_devices}->{$hash_key}->{'status'};,和$self->{_devices}{$hash_key}{'status'};一样,其实是在打印值。