Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: group based array sort

by artist (Parson)
on Feb 19, 2004 at 20:23 UTC ( #330345=note: print w/replies, xml ) Need Help??

in reply to group based array sort

Assuming you have data in given format. It would be easy to remember the parent. You don't need recursion in that case. You don't even need to mention the name of the parent. In the ouptut, you are given the order,level and parent information. Which you can format the way you like.
use strict; use warnings; my %Entry; $Entry{-1} = ''; my @list; my $id; while(<DATA>){ chomp; last if /OUTPUT/; my $entry = $1 if /\b(\w+)$/; my $level = () = $_ =~ m[\-]g; my $item; $Entry{$level} = $entry; #Remember the last entry $item->{id} = ++$id; $item->{name} = $entry; $item->{parent} = $Entry{$level-1}; $item->{level} = $level; push @list,$item; } foreach my $item (@list){ print join "|", map { $item->{$_} } qw(id level name parent); print "\n"; } __DATA__ foo ->bar -->troz ->narf __OUTPUT__ 1|0|foo| 2|1|bar|foo 3|2|troz|bar 4|1|narf|foo

Replies are listed 'Best First'.
Re: Re: group based array sort
by bageler (Hermit) on Feb 19, 2004 at 21:52 UTC
    that's good and fine if the data came in the sorted tree order, which it doesn't in my situation. :-) think like pulling from a database, where the order is unknown and i'm not allowed to do ORDER BY in my sql.
      While I really think using Sort::Tree is probably the best option, here is a purely iterative solution. It has the following requirements:
    • IDs will always be numerical
    • Root level nodes will always have a parent of 0
    • Probably a few others Cheers - L~R
        thanks! I'll give them both a shot.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://330345]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2018-03-24 12:52 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (298 votes). Check out past polls.