|Perl Monk, Perl Meditation|
Generating a Hash of Hashes Recursively to Display Database Hierarchyby c4onastick (Friar)
|on Jun 22, 2009 at 21:19 UTC||Need Help??|
c4onastick has asked for the
wisdom of the Perl Monks concerning the following question:
I've been trying to write a recursive function to generate a hash of hashes with little luck. (Recursive functions seem to be my nemesis as of late...) I'm parsing some hierarchical data from a database and trying to display it in a Win32::GUI::Treeview.
I've written a recursive function to populate the TreeView given input that looks like this:
Which works great and looks like this:
However, I'm having trouble getting the data out of the database to look like the input up there to feed into hashref_to_treeview. I was able to replicate the behavior I would like with a nasty set of nested foreach loops, but after finishing it looked terrible to maintain and decidedly un-perl-ish. I've summarized the flow below in pseudo-perl.
I set up a slightly less ugly set of joins on the tables in question to return the values like this:
This seems a bit easier since the SQL changes for each level of recursion which I'd have to deal with in the function. The join's output could be returned with DBI's selectall_arrayref and then I can just recurse through each array. But I've gotten stuck on how to make that data look like the structure above. My most recent attempt looked something like this:
Which doesn't work as well as I'd hoped and leads me to my question: How can I return data structures through recursion so I can build the hash above? Also, any other suggestions for a more painless way to do this would be welcomed!
Thanks in advance for your help!