Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Creating a tree from a parent child list, that also includes node specific properties... (classy)

by ikegami (Patriarch)
on Jun 29, 2009 at 15:51 UTC ( [id://775718]=note: print w/replies, xml ) Need Help??


in reply to Creating a tree from a parent child list, that also includes node specific properties...

use strict; use warnings; use DBI qw( ); use Tree::Simple qw( ); { package Fruit; use Data::Dumper qw( Dumper ); sub new { my $class = shift; bless({@_}, $class) } sub dump { my ($self, $prefix) = @_; local $Data::Dumper::Useqq = 1; local $Data::Dumper::Terse = 1; local $Data::Dumper::Indent = 1; local $Data::Dumper::Pad = $prefix; local $Data::Dumper::Sortkeys = sub{[qw( Parent Child Desc Property1 Property2 )]}; return Dumper($self); } } sub treeify { my ($sth) = @_; my $tree = Tree::Simple->new(undef); my %children; while (my $row = $sth->fetchrow_hashref()) { my ($id, $parent_id) = @$row{qw( Child Parent )}; my $parent = ( defined($parent_id) ? $children{$parent_id} ||= Tree::Simple->new(undef) : $tree ); my $node = $children{$id} ||= Tree::Simple->new(); $node->setNodeValue( Fruit->new(%$row) ); $parent->addChild( $node ); } return $tree; } sub dump_tree { my ($tree) = @_; $tree->traverse(sub { my ($node) = @_; my $prefix = "\t" x $node->getDepth(); print( $node->getNodeValue()->dump( $prefix ) ); }); } { my $sponge = DBI->connect( 'dbi:Sponge:', '', '', { RaiseError => 1 } ); my $sth = $sponge->prepare( 'SELECT * FROM Fruit', { NAME => [qw( Parent Child Desc Property1 +Property2 )], rows => [ [ undef, 50, 'Fruit', 'hidden', +'non-searchable' ], [ 50, 100, 'Apple', 'hidden', +'non-searchable' ], [ 100, 110, 'Granny Smith', 'Visible', +'searchable' ], ], } ); my $tree = treeify($sth); dump_tree($tree); }
  • Comment on Re: Creating a tree from a parent child list, that also includes node specific properties... (classy)
  • Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://775718]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-20 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found