On Fri, 6 Dec 2002, Andrew Beattie wrote:
> I have a hash.
>
> [% hash = { barney => 4, Wilma => 3, fred => 2, betty => 1 } %]
>
> It is easy to dump the contents of the hash ordered by the keys:
>
> [% FOREACH key = hash.keys.sort %]
> [% key %] => [% hash.$key %]
> [% END %]
>
> But I'm coming unstuck when I try to do it ordered by the values:
>
> [% FOREACH value = hash.values.nsort %]
> [% # key ? %] => [% value %]
> [% END %]
>
> Sure, I can find the values, how can I get the keys back?
I do this with two virtual hash methods called vsort and nvsort:
$Template::Stash::HASH_OPS->{ vsort } =
sub {
my $hash = shift;
return [ sort { $hash->{$a} cmp $hash->{$b} } keys %{$hash} ];
};
$Template::Stash::HASH_OPS->{ nvsort } =
sub {
my $hash = shift;
return [ sort { $hash->{$a} <=> $hash->{$b} } keys %{$hash} ];
};
Then in the template:
[% hash = { barney => 4, Wilma => 3, fred => 2, betty => 1 } -%]
[% FOREACH key = hash.nvsort -%]
[% key %] => [% hash.$key %]
[% END %]
which should produce:
betty => 1
fred => 2
Wilma => 3
barney => 4
Of course this only works for simple hashes in which every value is
a scalar...
HTH,
Dave
/L\_/E\_/A\_/R\_/N\_/T\_/E\_/A\_/C\_/H\_/L\_/E\_/A\_/R\_/N\
Dave Cash Power to the People!
Frolicking in Fields of Garlic Right On-Line!
[EMAIL PROTECTED] Dig it all.
_______________________________________________
templates mailing list
[EMAIL PROTECTED]
http://lists.ourshack.com/mailman/listinfo/templates