我很难弄清楚如何创建几个%th2结构(见下文),每个结构都是$th1{0}、$th1{1}等的值。
我还试图弄清楚如何遍历第二个散列%th2中的键。我遇到了一个经常被讨论的错误,
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.
}发布于 2013-07-31 12:02:57
更改:
$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-31 16:17:47
%th2的引用。(标量上下文中的%th2返回一个包含哈希内部信息的奇怪字符串。)$key1是一个字符串,而不是哈希引用。$key2是一个字符串,而不是哈希引用。https://stackoverflow.com/questions/17969791
复制相似问题