Reputation: 9
I want all nodes of each key sorted by key in hash ref or array or something like so that I can iterate that according to my need since I have to display each key with its all children. following is my data structure:
$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'
},
};
I have used following functions :
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;
}
here it returns a string with comma separated but I need some kind of data structure so that I can able to find all children for each key (in the form of hash ref or array) like:
Parent-1 -> [child-1,child-2, first child of child-2, second child of child-2]
Parent-2
Parent-3
Parent-4
any one can help me out? thanks in advance.
Upvotes: 0
Views: 592
Reputation: 326
You may also find brian d foy's answer on checking key existence useful
The code for with code for walking a data structure and Data::Diver may give you all the help you need.
Upvotes: 0
Reputation: 805
If your only goal is to display the hash contents, you should use the Data::Dumper module. It can be used to print data structures of arbitrary complexity with a good format.
Upvotes: 1