2011-07-02 41 views
1

我在散列哈希中访问变量时遇到问题我不知道我做了什么错误。在调试hash%list1的值时会给出undef,所以我无法获取我的值。散列在哈希中的散列问题

use strict ; 
use warnings ; 
my $text = "The, big, fat, little, bastards"; 
my $Author = "Alex , Shuman ,Directory"; 
my %hashes = {1,2,3,40}; 
my %count =(); 
my @lst = split(",",$text); 
my $i = 0 ; 
my @Authors = split(",", $Author); 
foreach my $SingleAuthor(@Authors) 
{ 
    foreach my $dig (@lst) 
    { 

    $count{$SingleAuthor}{$dig}++; 
    } 
} 

counter(\%count); 

sub counter 
{ 
    my $ref = shift; 
    my @SingleAuthors = keys %$ref; 
    my %list1; 
    foreach my $SingleAuthor1(@SingleAuthors) 
    { 
    %list1 = $ref->{$SingleAuthor1}; 
    foreach my $dig1 (keys %list1) 
    { 

    print $ref->{$SingleAuthor1}->{$dig1}; 
    } 
} 


} 

回答

5

在两个地方,你正试图分配一个散列引用的散列,从而导致这样的警告:参考发现,甚至大小列表预期

这里有你需要两个编辑:

# I changed {} to(). 
# However, you never use %hashes, so I'm not sure why it's here at all. 
my %hashes = (1,2,3,40); 

# I added %{} around the right-hand side. 
%list1 = %{$ref->{$SingleAuthor1}}; 

对于复杂的数据结构的一个有用且简单的讨论参见perlreftut

通过删除中间变量,可以简化您的counter()方法,而不会丢失可读性。

sub counter { 
    my $tallies = shift; 
    foreach my $author (keys %$tallies) { 
     foreach my $dig (keys %{$tallies->{$author}}) { 
      print $tallies->{$author}{$dig}, "\n"; 
     } 
    } 
} 

或者,如YSTH指出,像这样的,如果你不需要按键:

foreach my $author_digs (values %$tallies) { 
     print $dig, "\n" for values %$author_digs; 
    } 
+1

如果$ author和$掏确实只用钥匙,它可以通过在值循环,而不是 – ysth

+0

@ysth好点的简化得多。 – FMc

4

当我跑到你的代码,Perl中告诉我的问题是什么。

$ ./hash 
Reference found where even-sized list expected at ./hash line 7. 
Reference found where even-sized list expected at ./hash line 30. 
Use of uninitialized value in print at ./hash line 34. 
Reference found where even-sized list expected at ./hash line 30. 
Use of uninitialized value in print at ./hash line 34. 
Reference found where even-sized list expected at ./hash line 30. 
Use of uninitialized value in print at ./hash line 34. 

如果不清楚,可以打开诊断程序以获得更详细的说明。应该看到的是 -

$ perl -Mdiagnostics hash 
Reference found where even-sized list expected at hash line 7 (#1) 
    (W misc) You gave a single reference where Perl was expecting a list 
    with an even number of elements (for assignment to a hash). This usually 
    means that you used the anon hash constructor when you meant to use 
    parens. In any case, a hash requires key/value pairs. 

     %hash = { one => 1, two => 2, }; # WRONG 
     %hash = [ qw/ an anon array/]; # WRONG 
     %hash = (one => 1, two => 2,); # right 
     %hash = qw(one 1 two 2);   # also fine