Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
more useful options
 
PerlMonks  

Re: group based array sort

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

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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 16: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.
      bageler,
      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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://330345]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.