我无法访问哈希值,但我不确定我做错了什么。我做了一些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";
}
任何帮助将不胜感激。
答案 0 :(得分:3)
$name
应该是$bear
子中的getTree
。
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
会有所帮助。