Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

(dkubb) Re: (2) Data structure transformation

by dkubb (Deacon)
on Apr 09, 2001 at 03:25 UTC ( [id://70888]=note: print w/replies, xml ) Need Help??


in reply to Data structure transformation

ar0n, I think you are on the right track. I also try to limit the usage of sythentic variables, however IMHO using hashes isn't as wasteful as you might think. Their ability for fast lookups and their natural grouping properties make them a perfect choice for this problem.

The key is to use the hash to group your data, then flatten it into an array when you are done. Please consider the following code:

my %departments; while($sth->fetch) { $departments{ $department }{department} ||= $department; push @{ $departments{ $department }{classes} }, { class => $class, department => $department, count => $count, }; }

Now you need to transform it into a structure that HTML::Template will understant and use. The entire first level of the hash, the keys, are redundant, and something we don't need now. So we'll slice it away and flatten the structure into and array reference:

$tmpl->param( departments => [values %departments], ); #Note: $tmpl is an HTML::Template object

Or if you'd like to sort the department output:

$tmpl->param( departments => [@departments{ sort keys %departments }], );

Update 1: Removed extra code that was not pertinent to the problem. Also, changed the while loop code to be closer in-line to what ar0n had.

Update 2: Added sort to flattening example.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://70888]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-19 01:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found