|We don't bite newbies here... much|
Build tree data structure from DB (flat) data; function golfby gryphon (Abbot)
|on Aug 30, 2006 at 15:32 UTC||Need Help??|
gryphon has asked for the
wisdom of the Perl Monks concerning the following question:
Greetings fellow monks,
After looking over a recent project, I noticed I had written similar code in several sections that effectively did the same thing: Grab data from a database (single query) and build a tree structure from that data. Each time, I was building a structure according to similar rules, so I decided to make a common function.
What I've come up with works, but it has some repeated code. But what concerns me the most is that it's more or less a foreach loop that pushes to an array... which makes me want to rewrite it as a map. Anyway, I've been looking at this for a while and am stuck. I'd like some pointers as to how I could improve the function.
What I'm trying to accomplish here is take data from a database call and build a tree from it based on key names. Here's some sample input:
Here's some sample output:
To call the function, I just pass in the data and the key name and sub-group name pairs I want, like this:
Going forward, I'm probably going to want to add the ability to pull multiple keys into a particular level, not just a single key; but that's really out of scope for what I'm trying to accomplish right now.
What sort of things should I do to make this function better? Thanks in advance for your suggestions.