如何构建哈希数据结构

时间:2013-07-31 12:00:25

标签: perl hashtable

我无法弄清楚如何创建多个%th2结构(见下文),每个结构都是$th1{0}$th1{1}的值,依此类推。

我也在试图弄清楚如何遍历第二个哈希%th2中的密钥。我遇到了SO中经常讨论的错误,

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

此外,当我为%th2中的每个密钥分配%th1时,我假设将其作为匿名哈希复制到%th1中,并且我没有像我一样重写这些值重复使用%th2

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.
}

2 个答案:

答案 0 :(得分:4)

变化:

$th1{$idx} = %th2;

为:

$th1{$idx} = \%th2;

然后你可以创建你的循环:

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

或..更明确地说:

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" );
    }
}

答案 1 :(得分:1)

  1. $th1{$idx} = %th2;
    

    应该是

    $th1{$idx} = \%th2;
    

    只有标量可以存储在哈希中,因此您希望存储对%th2的引用。 (标量上下文中的%th2返回一个包含有关散列内部信息的奇怪字符串。)

  2. keys %$key1
    

    应该是

    keys %{ $th1{$key1} }
    

    $key1是一个字符串,而不是对哈希的引用。

  3. $key2->{"status"}
    

    应该是

    $th1{$key1}{$key2}{"status"}
    

    $key2是一个字符串,而不是对哈希的引用。