2011-07-02 9 views
1

해시 해시에서 변수에 액세스 할 때 문제가 있습니다. 내가 잘못했는지 모르겠습니다. 해시 % list1의 값을 디버깅하는 동안 undef를 제공하므로 내 값을 가져올 수 없습니다. 두 장소에서perl의 해시 해시 문제

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

경우, 그것은 좋은 지적 @ysth 대신 – ysth

+0

값을 통해 반복에 의해 훨씬 더 단순화 할 수있다. – FMc

4

, 펄 문제가 있었다 정확히 나에게 말했다.

$ ./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