sonet said:
#items parent
01.attr 0
02.attr 0
04.attr 01.attr
03.attr 01.attr
06.attr 02.attr
07.attr 03.attr
08.attr 03.attr
09.attr 07.attr
=========================================
transform to this form
ps: The order must follow above
=========================================
01.attr
04.attr
03.attr
07.attr
09.attr
08.attr
02.attr
Hello,
I believe that the following code should fit the bill. It is a bit long
but it also performs some minimum data validation (you will notice that
I added to your data set).
use strict;
use warnings;
my %tree;
my $initialK;
my $K;
my $V;
my $MaxDepth = 10;
my $depth;
while (<DATA>)
{
my ($dt1,$dt2) = /(.*) (.*)/ or die;
$tree{$dt1} = $dt2;
}
sub modifyValue
{
if ($depth >= $MaxDepth )
{
$tree{$initialK} = "XXXXXXXXXXX: Following $initialK leads a Depth >
$MaxDepth\n";
}
else
{
if(!exists $tree{$V} and $V ne "0")
{
$tree{$initialK} = "YYYYYYYYYYY " . $tree{$initialK};
}
elsif ($V ne "0" )
{
$depth = $depth + 1;
$K = $V;
$V = $tree{$K};
$tree{$initialK} = $V . " " . $tree{$initialK};
modifyValue();
}
}
}
foreach my $key (sort hashValueDescendingNum(keys(%tree)))
{
$initialK = $key;
$K = $key;
$V = $tree{$key};
$depth = 0;
modifyValue;
$tree{$initialK} = $tree{$initialK} . " " . $initialK;
}
foreach my $key (sort hashValueAscendingNum(keys(%tree)))
{
if (substr($tree{$key},0,11) eq "XXXXXXXXXXX")
{
print "\nData set problem: $key may be nested to more than $MaxDepth
level deep!" ;
}
elsif (substr($tree{$key},0,11) eq "YYYYYYYYYYY")
{
print "\nData set problem: $key or one of its ancestor may not
have a root!" ;
}
else
{
my @spaces =split(/ /,$tree{$key});
print (" "x($#spaces-1) . $key . "\n");
}
}
sub hashValueDescendingNum
{
$tree{$b} cmp $tree{$a};
}
sub hashValueAscendingNum
{
$tree{$a} cmp $tree{$b};
}
__DATA__
01.attr 0
02.attr 0
04.attr 01.attr
03.attr 01.attr
06.attr 02.attr
07.attr 03.attr
08.attr 03.attr
09.attr 07.attr
10.attr 11.attr
a.attr 0
b.attr a.attr
c.attr b.attr
d.attr c.attr
e.attr d.attr
f.attr e.attr
g.attr f.attr
h.attr g.attr
i.attr h.attr
j.attr i.attr
k.attr j.attr
l.attr k.attr
Would that work for you?
MrReallyVeryNice