#!/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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |