2

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

我还试图弄清楚如何遍历第二个 hash 中的键%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.
}
4

2 回答 2

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" );
    }
}
于 2013-07-31T12:02:57.543 回答
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是一个字符串,而不是对哈希的引用。

于 2013-07-31T16:17:47.247 回答