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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.