Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (9)
As of 2016-10-25 11:45 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (317 votes). Check out past polls.