我有一个深度嵌套结构的散列。预先不知道嵌套的级别。但是每个级别都有两个属性“实例”和另一个“依赖关系”的散列。所以这是一种看起来像递归的散列。Perl:从子程序返回hashref
my $HASH = {
"top"=> {
"instance" => "top_instance",
"dependencies" => {
"sub_block1" => {
"instance" => "sub_block1_instance",
"dependencies" => {}
},
"sub_block2" => {
"instance" => "sub_block2_instance",
"dependencies" => {
"sub_block3" => {
"instance" => "sub_block3_instance",
"dependencies" => {}
}
}
}
}
}
};
我有一个子程序,它接受用户定义的字符串并从指定的层次结构中返回一个内部散列片段。
例如,如果用户指定 “sub_block2”,子程序应该返回这个哈希:
{
"sub_block2" => {
"instance" => "sub_block2_instance",
"dependencies" => {
"sub_block3" => {
"instance" => "sub_block3_instance",
"dependencies" => {}
}
}
}
}
这是我的子程序:
sub get_starting_point {
my $string = shift;
my $config = shift;
foreach my $key (keys %$config) {
if($key ne $string) {
# if current key is not what user asked for, recurse into next level of hierarchy
if (exists $$config{$key}{dependencies}) {
&get_starting_point($$config{$key}{dependencies});
}
} else {
# we found the key, return the hash under this hierarchy
my $tempHash = {$key => $$config{$key}};
print ref($tempHash); # correctly prints HASH
print Dumper($tempHash); # correctly prints out the sub-hash
return $tempHash; # I am expecting this return value to be a hash-ref
}
}
}
正如你可以看到,这是一个递归函数,它可以在哈希中深入潜入,直到遇到与参数相匹配的密钥并返回该密钥下的完整子哈希。
这就是我所说的这个子程序。
my $subHash = get_starting_point("sub_block2",$HASH);
print ref($subHash); # is not a ref
print Dumper($subHash); # prints nothing
我做错了什么!?!?
编辑:用我确切的问题更新了问题。看起来像我之前使用的一个简单示例,按照预期工作。
您显示的代码没有任何问题。复制并粘贴,添加导入,删除c样式注释(使用#for perl注释)并按预期打印。你能显示你的确切代码吗?你使用严格和warniings? – Nate 2014-11-21 01:24:37
我怀疑当你尝试*使用hashref;显示你在那里试着做什么。 http://perlmonks.org?node=References+quick+reference有一些有用的规则来弄清楚如何使用参考 – ysth 2014-11-21 01:40:10