in reply to Reorganizing the content of a file

G'day ovedpo15,

I used these steps:

  1. Read the file and collect all data in a hash.
  2. Generate arrays of ancestry elements for each ID.
  3. Sort array elements; join; print.

Here's the code:

#!/usr/bin/env perl use strict; use warnings; my $root = '#'; my %tree; while (<DATA>) { chomp; my ($id, $pid, $name) = split /,/; $tree{$id} = {name => $name, pid => $pid}; } my @paths; push @paths, concat($_, \%tree) for keys %tree; print join(',', @$_), "\n" for sort { @$a <=> @$b || $a->[0] cmp $b->[0] } @paths; sub concat { my ($id, $tree, $path) = @_; $path = [] unless defined $path; push @$path, $tree->{$id}{name}; if ($tree->{$id}{pid} ne $root) { concat($tree->{$id}{pid}, $tree, $path); } return $path; } __DATA__ 15,10,name3 10,#,name1 12,10,name2 5,12,name4 8,5,name5

Output:

name1 name2,name1 name3,name1 name4,name2,name1 name5,name4,name2,name1

Note that I changed the last line of your data: s/8,5,name4/8,5,name5/.

Also, it's completely unclear from your expected output, what ordering you wanted in the general case. I've written a sort to give the expected output for a single set of input data. Ask yourself if, given different input, "name2,name1" was "name2,name6,name1", what would the order be? Adjust my "sort { ... }" as required.

— Ken