2011-07-02 103 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