Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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


Comment on Re: group based array sort
Download Code
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.
      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
Node Status?
node history
Node Type: note [id://330345]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2014-11-27 19:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (187 votes), past polls