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.


In reply to (dkubb) Re: (2) Data structure transformation by dkubb
in thread Data structure transformation by ar0n

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.