Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Reorganizing the content of a file

by Laurent_R (Canon)
on Dec 18, 2018 at 17:35 UTC ( [id://1227413]=note: print w/replies, xml ) Need Help??


in reply to Reorganizing the content of a file

Another proposal:
use strict; use warnings; use feature 'say'; my %tree; while (<DATA>) { chomp; my ($id, $pid, $name) = split /,/; $tree{$id} = {pid => $pid, name => $name}; } for my $id (sort keys %tree) { my @parent_list; my $temp_id = $id; while (exists $tree{$temp_id}) { push @parent_list, $tree{$temp_id}{name}; $temp_id = $tree{$temp_id}{pid}; } say join ",", @parent_list; } __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

Replies are listed 'Best First'.
Re^2: Reorganizing the content of a file
by haj (Vicar) on Dec 18, 2018 at 18:37 UTC
    Amazing: Your output is sorted by id - alphabetically - and still gives the same ordering as sorting by names :)
      Yeah, right, lucky that the data happened to be like that. I really did not try very hard to sort, as the OP did not specify anything about that, I just included a sort on the keys to tidy up the output, and it turned out to be exactly the output sample provided in the OP.
        I really liked your solution. It simple, clear and easy to understand.
        It is not part of my original request but is it possible to change the sorting of the ids, so it will keep the same order, without depending on the lexicography order?
        If so, what change in code should I do?
        The only thing that comes to my mind, is to add a third field to each id that will represent the index. I don't care about the sibling's order, but it will be nice to see an order of parent-chlid.
        For example, if we have the following input:
        5,#,A 1,5,B 4,5,C 2,4,D
        The output should be:
        A B,A C,A D,C,A
        and not the following output:
        B,A D,C,A C,A A
        Please note that it does not matter for me the order of the sibling.
        Thank you for your help! :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1227413]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-26 00:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found