Sort::Tree - Organize list of objects into parent/child order.
use Sort::Tree; my @tree = list_to_tree(\@my_list, $id_field, $parent_field); my @sorted_list = tree_to_list(\@tree, [$id_field], [\&Sort::Tree::numerically], $parent_field));
Sort::Tree includes two routines, list_to_tree and tree_to_list. These are used to organize an unordered list of objects into a tree form. For example, you'd perform a database query to gain a list of folders in a document system, and then order them by parentage for display in a webpage.
use Sort::Tree; my @creatures = ( { id => 1, class => -1, name => 'animal' }, { id => 2, class => 1, name => 'mammal' }, { id => 3, class => 1, name => 'bird' }, { id => 4, class => 1, name => 'reptile' }, { id => 5, class => 2, name => 'primate' }, { id => 6, class => 2, name => 'feline' }, { id => 7, class => 5, name => 'human' }, { id => 8, class => 6, name => 'housecat' }, { id => 9, class => 3, name => 'penguin' }, { id => 10,class => 4, name => 'gecko' } ); my @tree = Sort::Tree::list_to_tree(\@creatures, 'id', 'class'); foreach my $row (Sort::Tree::tree_to_list(\@tree, ['id'], [\&Sort::Tree::numerically], 'class')) { print ' ' x $row->{class}, $row->{name}, "\n"; }
The following is displayed:
animal mammal primate human feline housecat bird penguin reptile gecko
Takes a list of queried objects and builds a tree, resorting it into tree order and including the nesting level. Inspired by DBIx::Tree.
Takes a tree and serializes it into a sorted list. Recursive. Inspired by DBIx::Tree (but not derived from it)
Parameters: $tree - the tree data structure $cmpFields - Field to do comparison on (default idField) $cmpFuncs - Ordering function (default &numerically) $idField - $depth - Depth to display (default 0) $max_depth - Maximum depth to display; -1 for all (default -1)
Nothing outside of the normal Perl core modules (Exporter & Carp).
In tree_to_list, various ordering mechanisms are permitted, but only the 'numerically' option works.
1.07 - Released on 2003/06/19.
perl(1)
Bryce Harrington <brycehar@bryceharrington.com>
http://www.osdl.org/
Copyright (C) 2003 Bryce Harrington. All Rights Reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Revision: $Revision: 1.1.1.1 $
To install Sort::Tree, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sort::Tree
CPAN shell
perl -MCPAN -e shell install Sort::Tree
For more information on module installation, please visit the detailed CPAN module installation guide.