Perl中散列数组树的路径列表 [英] List of paths into hash array tree in Perl
问题描述
我有一系列的路径
C:\A
C:\B\C
D:\AB
我想将它们放在哈希数组树中,以便可以在TT2模板中进行遍历.
and I'd like to have these in a hash array tree so I can go through them in a TT2 template.
我的意思是这样的:
@dirs = [
{
name => "C:",
subs => [
{
name => "A",
subs => [],
},
{
name => "B",
subs => [
{
name => "C",
subs => [],
}
],
}
]
},
{
name => "D:",
subs => [
{
name => "AB",
subs => [],
}
],
}
]
我也知道我可能在这里做Brainderp,所以我对其他方法持开放态度,唯一的要求就是将路径列表转换为可以使用TT2模板工具包重建为树的内容.
I also know that I'm probably doing brainderp here so I'm open to other approaches, only requirement is turning that list of paths into something you can rebuild as a tree with the TT2 Template Toolkit.
那个结构又叫什么?我只是想到哈希数组树,但我敢打赌这是错误的.
Also what's that structure called? I just thought of hash array tree but I bet that's wrong.
推荐答案
我做了一个复杂的哈希结构来跟踪已经放置的节点,然后我做了一个.步骤更多,但代码更精简.
I did one with a complex hash structure keeping track of already placed nodes, and then I did this one. More steps, but somewhat leaner code.
while ( <> ) {
chomp;
my $ref = \@dirs;
foreach my $dir ( split /\\/ ) {
my $i = 0;
$i++ while ( $ref->[$i] and $ref->[$i]{name} ne $dir );
my $r = $ref->[$i] ||= { name => $dir, subs => [] };
$ref = $r->{subs};
}
}
这篇关于Perl中散列数组树的路径列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!