这是一个非常简短的方法。请注意,这只能如此简单,因为我将您的数据格式更改为与您的树结构完美匹配的哈希值的哈希值。请参阅下面的代码将生成的结构转换为您的结构。
my $tree = {root => {}};
foreach my $input (<DATA>) { chomp $input;
my $t = $tree;
$t = $t->{$_} //= {} for split /\\/ => $input;
}
use Data::Dumper; print Dumper $tree;
__DATA__
C:\A
C:\B\C
D:\AB
C:\B\A
C:\B\A\C
Output:
$VAR1 = {
'C:' => {
'A' => {},
'B' => {
'A' => {
'C' => {}
},
'C' => {}
}
},
'D:' => {
'AB' => {}
}
};
要将这个数据结构转换为您的数据结构,只需使用以下代码:
sub transform {
my $tree = shift;
my @children = ();
while (my ($name, $children) = each %$tree) {
push @children, {
name => $name,
subs => [ transform($children) ],
}
}
return @children;
}
my $AoH_tree = {name => 'root', subs => [transform($tree)] };
完毕。 :) 对于一种完全不同的方法,具有更多的糖分、功能和可读性,但更多的 LOC,请参阅我的其他答案 https://stackoverflow.com/a/13208927/1184510.