首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何建立哈希数据结构

如何建立哈希数据结构
EN

Stack Overflow用户
提问于 2013-07-31 12:00:25
回答 2查看 82关注 0票数 2

我很难弄清楚如何创建几个%th2结构(见下文),每个结构都是$th1{0}$th1{1}等的值。

我还试图弄清楚如何遍历第二个散列%th2中的键。我遇到了一个经常被讨论的错误,

Can't use string ("1") as a HASH ref while "strict refs" in use

另外,当我将%th2分配给%th1中的每个密钥时,我假设这是作为匿名散列复制到%th1中的,并且在重用%th2时不会高估这些值。

代码语言:javascript
复制
use strict;

my %th1 = ();
my %th2 = ();
my $idx = 0;

$th2{"suffix"} = "A";
$th2{"status"} = 0;
$th2{"consumption"} = 42;

$th1{$idx} = %th2;

$idx++;

$th2{"suffix"} = "B";
$th2{"status"} = 0;
$th2{"consumption"} = 105;

$th1{$idx} = \%th2;

for my $key1 (keys %th1)
{
    print $key1."\n\n";
    for my $key2 (keys %$key1)
    {
      print $key2->{"status"};
    }

    #performing another for my $key2 won't work. I get the strict ref error.
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-31 12:02:57

更改:

代码语言:javascript
复制
$th1{$idx} = %th2;

至:

代码语言:javascript
复制
$th1{$idx} = \%th2;

然后,您可以创建您的循环如下:

代码语言:javascript
复制
for my $key1 (keys %th1) {
    for my $key2 (keys %{$th1{$key1}} ) {
        print( "Key1=$key1, Key2=$key2, value=" . $th1{$key1}->{$key2} . "\n" );
    }
}

或者..。更明确地:

代码语言:javascript
复制
for my $key1 (keys %th1) {
    my $inner_hash_ref = $th1{$key1};

    for my $key2 (keys %{$inner_hash_ref}) {
        print( "Key1=$key1, Key2=$key2, value=" . $inner_hash_ref->{$key2} . "\n" );
    }
}
票数 4
EN

Stack Overflow用户

发布于 2013-07-31 16:17:47

  1. $th1{$idx} = %th2; 应该是 $th1{$idx} =Th2; 只有标量可以存储在散列中,因此要存储对%th2的引用。(标量上下文中的%th2返回一个包含哈希内部信息的奇怪字符串。)
  2. 键%$key1 1 应该是 键%{ $th1{$key1} } $key1是一个字符串,而不是哈希引用。
  3. $key2->{"status"} 应该是 $th1{$key1}{$key2}{“状态”} $key2是一个字符串,而不是哈希引用。
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17969791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档