Offering an object-oriented version (Taking some liberties offered by perl over "strict OO"):
#!/usr/bin/env perl use strict; use warnings; {package Item; my %By_id; # Collection sub new{ my ($class,%attr) = @_; die "ID is required" unless $attr{id}; return $By_id{$attr{id}}=bless \%attr, $class; } sub GetParentObj{ return undef if $_[0]->{parent} eq "#"; # Root has no parent return $By_id{ $_[0]->{parent} }; } sub GetRoot{ # CLASS method return $By_id{"#"}; } sub GetChildren{ my ($self) = @_; return grep {$_->{parent} == $self->{id}} values %By_id; } sub GetAncestors{ my ($self) = @_; my @ancestors; my $parent = $self; while ($parent = $parent->GetParentObj()){ push @ancestors, $parent; } return @ancestors; } sub GetAll{ # CLASS method my ($sort_att) = @_; $sort_att ||= "name"; # Defaults to name-based return sort {$a->{$sort_att} cmp $b->{$sort_att} } values %By_id; } } # -- Main Code ----- while (<DATA>) { chomp; my ($id, $pid, $name) = split /,/; Item::->new(id=>$id, parent=>$pid, name=>$name); } for my $item (Item::GetAll("name")){ print $item->{name}, map({"," . $_->{name}} $item->GetAncestors()), "\n"; } __DATA__ 15,10,name3 10,#,name1 12,10,name2 5,12,name4 8,5,name5

                As a computer, I find your faith in technology amusing.


In reply to Re: Reorganizing the content of a file by NetWallah
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.