-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;
}

当我迭代哈希中的键时,我可以访问该列表,但不能直接访问。所以我假设它与我从“keys() 循环”中获取值的方式有关

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";

}

任何帮助,将不胜感激。

4

1 回答 1

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 strict并且use warnings会有所帮助。

于 2012-10-01T20:23:15.220 回答