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);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.