punch_card_don has asked for the wisdom of the Perl Monks concerning the following question:

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.

Replies are listed 'Best First'.
Re: Template Toolkit foreach hash key sort numerical instead of ascii?
by philcrow (Priest) on Apr 17, 2007 at 18:02 UTC
    You probably only need to replace sort with nsort. If that is not enough, you could create your own virtual method.

    Phil

    The Gantry Web Framework Book is now available.
Re: Template Toolkit foreach hash key sort numerical instead of ascii?
by punch_card_don (Curate) on Apr 17, 2007 at 18:00 UTC
    Uh, found it:

    http://www.template-toolkit.org/docs/default/Manual/VMethods.html

    sort, nsort

    Return a list of the keys, sorted alphabetically (sort) or numerically (nsort) according to the corresponding values in the hash.




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