Monumental Monks,

Using Tempalte Toolkit's 'foreach' to output the contents of a hash into a table, where the key is numeric adn applying the sort operator to the keys. Well of course I'm getting an ascii-sort (1, 10, 11, 12, 2, 20, 21,...) instead of a numerical sort (1, 2, 3..., 9, 10, 11..., 19, 20, 21...)

In Perl, we can do

foreach $key (sort {$a <=> $b} keys %myhash) { do stuff; }

Is there any way to apply this kind of thing to the TT foreach loop?

Thanks.

Sample code:
Perl Script

$sql = "SELECT record_id, attribute_1, attribute_2 FROM theTable"; $sth = $dbh->prepare($sql) or die("Could not prepare!" . $dbh->errstr) +; $sth->execute() or die("Could not execute!" . $dbh->errstr); while ($record_id, $att_1, $att_2) = $sth->fetchrow_array()) { $data_hash{$record_id} = { att_1 => $att_1, att_2 => $att_2 }; } $vars = { data_hash => \%data_hash }; $template->process($template_file, $vars) || die "Template process failed: ", $template->error(), "\n";

Template:

<table class="myClass"> [% FOREACH record_id IN data_hash.keys.sort.reverse %] <tr><td>$data_hash.$record_id.att_1</td><td>$data_hash.$record_id +.att_2</td></tr> [% END %] </table>



Forget that fear of gravity,
Get a little savagery in your life.

In reply to Template Toolkit foreach hash key sort numerical instead of ascii? by punch_card_don

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.