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.