For the unimaginative ones: The last input line ought to end in name5.
A rather simple solution would use more than one hash (or array). Actually, both structures are fine. If your biggest id is much larger than the number of names then hashes might be more effective. The following isn't optimized because it unravels the ancestry several times - if performance is an issue than this could be avoided (with a bit of recursion).
use strict; use warnings; my %parent_id = (); my %id_to_name = (); # Building the tree while (my $line = <DATA>) { chomp $line; my ($id,$parent_id,$name) = split /,/, $line; $parent_id{$id} = $parent_id; $id_to_name{$id} = $name; } # Dumping the tree my %name_to_id = reverse %id_to_name; for my $name (sort keys %name_to_id) { my $id = $name_to_id{$name}; my $parent_id = $parent_id{$id}; my @ancestors = ($name); while (my $name = $id_to_name{$parent_id}) { push @ancestors,$name; $parent_id = $parent_id{$parent_id}; } print join(',',@ancestors),"\n"; } __DATA__ 15,10,name3 10,#,name1 12,10,name2 5,12,name4 8,5,name5
In reply to Re: Reorganizing the content of a file
by haj
in thread Reorganizing the content of a file
by ovedpo15
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |