我希望每个键的所有节点都按散列、ref或数组中的键排序,这样我就可以根据需要进行迭代,因为我必须显示每个键及其所有子键。以下是我的数据结构:
$hash1 = {
'3' => {
'title' => 'Parent-3',
'parentid' => '-1'
},
'1' => {
'children' => {
'11' => {
'title' => 'child-1',
},
'5' => {
'children' => {
'8' => {
'title' => 'first child of child-2',
},
'13' => {
'title' => 'second child of child-2',
}
},
'title' => 'child-2',
}
},
'title' => 'Parent-1',
'parentid' => '-1'
},
'2' => {
'title' => 'Parent-2',
'parentid' => '-1'
},
'4' => {
'title' => 'Parent-4',
'parentid' => '-1'
},
};我使用了以下函数:
sub Options {
my $hash = shift;
my $options = '';
my $iter; $iter = sub {
my $hash = shift;
my $indent = shift || '';
foreach my $k (sort {$a <=> $b} keys %{$hash}) {
my $v = $hash->{$k};
if($v->{parentid} eq '-1'){
$options .= $v->{title} ."-parent\n";
}else{
$options .= $v->{title} . "," ;
}
if ($v->{children}){
$iter->($v->{children}, $indent . "");
}
}
chop($options);
$options .= "\n";
};
$iter->($hash);
return $options;
}在这里,它返回一个逗号分隔的字符串,但我需要某种数据结构,以便能够找到每个键的所有子键(以散列、ref或数组的形式),如下所示:
Parent-1 -> [child-1,child-2, first child of child-2, second child of child-2]
Parent-2
Parent-3
Parent-4有谁能帮我吗?提前谢谢。
发布于 2013-09-19 17:45:58
如果您的唯一目标是显示散列内容,则应该使用the Data::Dumper module。它可以用来打印任意复杂的数据结构和良好的格式。
发布于 2013-09-20 01:28:36
您可能还会发现brian d foy's answer on checking key existence很有用
的代码和用于遍历数据结构和Data::Diver的代码可以为您提供所需的所有帮助。
https://stackoverflow.com/questions/18888713
复制相似问题