I'm working on a student registration application for my school, which uses HTML::Template.

It grabs data from a database and needs to transform that data into a data structure that HTML::Template can use.

Each row looks like this:
while ( $sth->fetchrow() ) { push @classes, { class => $class, department => $department, count => $count }; }
The structure my template needs looks like this:
@departments = ( { department => "v6" classes => [ { class => "Chemistry", department => "v6", count => 18 }, { class => "German I", department => "v6", count => 27 }, etc ... ] }, { department => "h4" classes => [ { class => "French II", department => "h4", count => 9 }, etc ... ] }, etc ... );
Now, to get to the point; I'm using the following to get what I want:
my %departments; push @{ $departments{ $_->{department} }{classes} }, $_ foreach (@clas +ses); my @departments = map { $_->{department} = $_->{classes}[0]{department}; $_ } values %departments;
And it works, but.... it just rubs me the wrong way (take that Christina Aguilera!). It's icky. I don't like that temporary hash very much.

Is there a more efficient/prettier way of getting what I want? I'm not really aiming for high-performance, since the query I'm using will never return over a 1000 records, but I'm curious...

Thanks.

[ar0n]


In reply to 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.