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); }

In reply to Re: Creating a tree from a parent child list, that also includes node specific properties... (classy) by ikegami
in thread Creating a tree from a parent child list, that also includes node specific properties... by bryank

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.