in reply to Generating recursive hash

To what end? What do you want to achieve using the data structure? What form is your "data structure" actually in? Are you sure you actually want a hash?


True laziness is hard work

Replies are listed 'Best First'.
Re^2: Generating recursive hash
by Anonymous Monk on Dec 12, 2009 at 15:00 UTC

    unfortunately I cannot tell to what end, it might be 3 levels deep or more so I don't want to hard code it.

    I actually have these info in a mysql db, what I would want to do is pulling those data, build the hash so I can display them in a nicely formatted structure.

    root - first level -- second level --- third level - first

    and so on, I am using Template Toolkit and I figured out that I can display it this way using "VIEWS" but I have no idea how to sort up this mess.

    Note that both the 'id' & 'name' fields are important (the name so a user can understand what this section is and the ID for editing it)

      I know nothing about TT and having glanced at the documentation I really don't want to get up to speed with it for this exercise. However the following may get you headed in a useful direction:

      use strict; use warnings; use DBI; my $tmpFileName = 'temp'; open my $outFile, '>', $tmpFileName or die "Can't open $tmpFileName: $ +!\n"; print $outFile $_ for <DATA>; close $outFile; my $dbh = DBI->connect ("DBI:CSV:") or die "DBI connect failed: $DBI::errstr"; my $sth = $dbh->prepare ("SELECT * FROM temp"); my @structure; my %idMap; $sth->execute (); while (my $row = $sth->fetchrow_hashref) { my ($id, $name, $parent) = @{$row}{'id', 'name', 'parent'}; if (! $parent) { push @structure, {id => $id, name => $name, children => []}; $idMap{$id} = $structure[-1]; next; } if (exists $idMap{$parent}) { push @{$idMap{$parent}{children}}, {id => $id, name => $name, +children => []}; $idMap{$id} = $idMap{$parent}{children}[-1]; next; } die "Can't handle children id provided before parent"; } $sth->finish (); $dbh->disconnect (); print dumpChildren($_) for @structure; sub dumpChildren { my ($node, $indent) = @_; $indent ||= ''; my $str = "$indent$node->{name}\n"; $indent .= ' '; $str .= dumpChildren ($_, $indent) for @{$node->{children}}; return $str; } __DATA__ id,name,parent 1,data1,0 2,data2,1 3,data3,1 4,data4,3 5,data5,4

      Prints:

      data1 data2 data3 data4 data5

      True laziness is hard work