I suspect an array will be not enough..
More: depending on the order your elements are delcared you may need two parse of the same data. Hashes are useful. Hashes of Hashes (HoH see perldsc ) are powerful.
In plain english would be something like:
Build up a hash to hold association of names with their characteristics by id (HoH: $assoc{ $current_id } = { name => $current_name, $parent => $current_parent } ) Add an exception: if parent is pound put an empty string or undef.
Now you have to recurse the above structure to build up the list of ancestors: foreach id print the name and if has a parent, get the name of his parent and if the latter has a parent get the name of this parent too, and if the latter has a parent...
Recursion! A sub that call itself.. See https://perlmaven.com/recursive-subroutines
UPDATE 21:30 gmt+1 as many monks provided their solution, here is mine, traslating in perl what above stated in english:
use strict; use warnings; my %assoc; while(<DATA>){ chomp; my @fields = split ',',$_; $assoc{ $fields[0] } = { name => $fields[2], parent => $fields[1] eq '#' ? '' : $fields[1], } } sub get_parents{ my $href = shift; # exit condition first in recursive subs return '' unless defined $assoc{ $href->{parent} }{name}; print "$assoc{ $href->{parent} }{name} "; # recursive call get_parents( $assoc{ $href->{parent} } ); } foreach my $id (keys %assoc){ print "$assoc{$id}->{name} "; get_parents($assoc{$id}); print "\n"; } __DATA__ 15,10,name3 10,#,name1 12,10,name2 5,12,name4 8,5,name5 #output name4 name2 name1 name1 name5 name4 name2 name1 name2 name1 name3 name1
L*
In reply to Re: Reorganizing the content of a file
by Discipulus
in thread Reorganizing the content of a file
by ovedpo15
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |