* Andrew Beattie <[EMAIL PROTECTED]> [2002-12-06 08:43]:
> I have a hash.
Hashes are nice.
> [% 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?
No, but this is a Perl issue, not a TT one. You can reverse the hash
[%
nhash = { };
keys = hash.keys;
values = hash.values;
FOREACH v = values;
nhash.$v = keys.${loop.index};
END;
%]
And then do things with nhash and hash in parallel.
As an aside, might it make sense to have a hash virtual method reverse,
which does, effectively, %hash = reverse %hash? Patch attached.
If this is applied, then getting the keys from the value would be:
hash = { one => 1, two => 2 };
rhash = hash.reverse;
dumper.dump(rhash);
$VAR1 = {
'1' => 'one',
'2' => 'two'
};
This will do Silly Things if there are nested arrays, though:
[%
hash = { foo => [ 1 2 3 ] };
rhash = hash.reverse;
dumper.dump(rhash);
%]
$VAR1 = {
'ARRAY(0x833dcd8)' => 'foo'
};
Cc'est la vie.
(darren)
--
Alden's Laws:
(1) Giving away baby clothes and furniture
is the major cause of pregnancy.
(2) Always be backlit.
(3) Sit down whenever possible.
Index: Stash.pm
===================================================================
RCS file: /template-toolkit/Template2/lib/Template/Stash.pm,v
retrieving revision 2.71
diff -u -r2.71 Stash.pm
--- Stash.pm 2002/11/04 19:46:05 2.71
+++ Stash.pm 2002/12/06 14:21:13
@@ -140,6 +140,11 @@
my ($hash) = @_;
[ sort { $hash->{$a} <=> $hash->{$b} } (keys %$hash) ];
},
+ 'reverse' => sub {
+ my $hash = shift;
+ my %nhash = reverse %$hash;
+ return \%nhash;
+ },
defined $HASH_OPS ? %$HASH_OPS : (),
};
@@ -951,4 +956,3 @@
=head1 SEE ALSO
-L<Template|Template>, L<Template::Context|Template::Context>
\ No newline at end of file