2012-10-01 137 views
-2

我无法访问散列值,我不知道我在做什么错误。我做了一些Perl,但没有太多的哈希。在散列哈希中访问值

我试图访问散列哈希散列值。

这里是我建的哈希

sub buildList 
{ 
    my ($name,$gender,$father,$mother,$age); 
    my %bear_ref=(); 

    open IN, "<input.txt" or die "can't open file"; 

    while(<IN>) { 
     ($name, $gender, $father, $mother, $age) = split(/:/); 
     $bear_ref{ $name } { 'gender' } = $gender; 
     $bear_ref{ $name } { 'mother' } = $father; 
     $bear_ref{ $name } { 'father' } = $mother; 
     $bear_ref{ $name } { 'age' } = $age; 
    } 
    close IN; 
    return \%bear_ref; 
} 

当我通过按键中的散列itereting但不直接,我可以访问列表。所以我假设它是与我是从获取价值的方式“键()循环”

for my $name (keys %$ref) { 
    $father= $ref->{ $name }->{ 'father'}; # works 
    $mother= $ref->{ $name }->{ 'mother'}; # works 
    getTree($name, $ref); 
} 

sub getTree 
{ 
    my $bear = shift; 
    my $ref = shift; 
    my ($father, $mother); 
    $father= $ref->{ $name }->{ 'father'}; # doesn't work...have also tried with %$ref-> 
    $mother= $ref->{ $name }->{ 'mother'}; # doesn't work...have also tried with %$ref-> 
    print "$father : $mother\n"; 

} 

任何帮助,将不胜感激。

+2

总是['use strict;'](http://perldoc.perl.org/strict.html)和['use warnings;'](http://perldoc.perl.org/warnings.html)直到你确切知道它为什么被推荐。 –

回答

3

$name应该是$beargetTree子。

sub getTree 
{ 
    my $bear = shift; 
    my $ref = shift; 
    my ($father, $mother); 
    ## note that I am using $bear instead of $name since $name is not defined 
    $father= $ref->{ $bear }->{ 'father'}; 
    $mother= $ref->{ $bear }->{ 'mother'}; 
    print "$father : $mother\n"; 
} 

注:use strictuse warnings将是有益的。

+0

哇,好吧,现在我觉得哑巴。谢谢。是的,我使用严格和警告,但我忘了把输出。无论哪种方式,我想我现在拥有它。再次感谢。 – user1712832