2011-06-10 206 views
2

我在这里看到过类似的问题,但是没有一个可以专门回答我自己的问题。哈希的Perl哈希问题

我试图以编程方式创建哈希散列。我的问题代码如下:

my %this_hash =(); 
if ($user_hash{$uuid}) 
{ 
    %this_hash = $user_hash{$uuid}; 
} 

$this_hash{$action} = 1; 

$user_hash{$uuid} = %this_hash; 
my %test_hash = $user_hash{$uuid}; 
my $hello_dumper = Dumper \%this_hash; 

根据我的输出,$ this_hash被正确分配,但

$user_hash{$uuid} = %this_hash 

正显示出在调试器1/8的值;不知道他的意思。我也得到一个警告:“哈希赋值中奇数个元素...”

+1

另请参阅http://perldoc.perl.org/perldiag.html获取错误消息,以及http://perldoc.perl.org/index-tutorials.html获取关于数据结构的几个教程。 – FMc 2011-06-10 22:07:21

回答

12

任何时候你写

%anything = $anything 

你做错了什么。几乎任何时候你写

$anything = %anything 

你做错了什么。这包括$anything是数组或哈希访问(即$array[$index]$hash{$key})。存储在数组和散列中的值总是标量,而数组和哈希本身不是标量。所以,当你想在一个散列中存储一个散列时,你将一个引用存储到它:$hash{$key} = \%another_hash。而当你想要访问散列中存有引用的散列时,你可以解除引用:%another_hash = %{ $hash{$key} }$hashref = $hash{$key}; $value = $hashref->{ $another_key }$value = $hash{$key}{$another_key}

为了适应参考的速度,我强烈建议您阅读Perl References TutorialPerl Data Structures Cookbook

+1

已经发生了很多学习。谢谢你的答案。 – SemperFly 2011-06-10 22:14:59

5

这不是一个“散列哈希”;这是一个“散列引用散列”。

尝试:

$user_hash{$uuid} = \%this_hash; 
+0

感谢Nemo的回答。 – SemperFly 2011-06-10 22:14:48