[Templates] Serious problem with sorting hash of hashes
Tim MacKenzie
Tim.MacKenzie@fulcrum.com.au
Mon, 4 Mar 2002 10:21:00 +1100
On Mon, Mar 04, 2002 at 11:50:02PM +0100, SoCo wrote:
> I have topic problem, coz i'm getting this error:
>
> undef error - Can't use string ("7") as a HASH ref while "strict refs" in
> use at /usr/lib/perl5/site_perl/5.6.1/i386-linux/Template/Stash.pm line 161.
>
> while using nsort on:
> [% FOREACH sec_hash = pri_hash.keys.nsort('sec_hash_key') %]
pri_hash.keys is a list of scalars nsort(key) expect a list of hashes.
You probably meant to say:
[% FOREACH sec_hash = pri_hash.nsort('sec_hash_key') %]
but this wouldn't work either since the HASH sort doesn't take an argument
like the ARRAY sort does (a deficiency in the core I think).
I have added functions to do some more useful sorts:
These could all be rolled into the core sort and nsort functions as 1 and
2 argument variants.
# Sort a list of keys using sort field in a hash.
$Template::Stash::LIST_OPS->{'sorthash'} = sub {
my ($list, $hash, $key) = @_;
[ sort { lc $hash->{$a}{$key} cmp lc $hash->{$b}{$key} } @$list];
};
# Return keys of hash sorted by sort field in referenced hash.
$Template::Stash::HASH_OPS->{'sort1'} = sub {
my ($hash, $key) = @_;
[ sort { lc $hash->{$a}{$key} cmp lc $hash->{$b}{$key} } (keys %$hash)];
};
# Return keys of hash sorted numerically by sort field in referenced hash.
$Template::Stash::HASH_OPS->{'nsort1'} = sub {
my ($hash, $key) = @_;
[ sort { $hash->{$a}{$key} <=> $hash->{$b}{$key} } (keys %$hash)];
};
It would be nice if the core also supplied other basic perl functionality
such as SCALAR.substr, LIST.splice, etc.
Tim
--
~ Specialists in IT Infrastructure ~
* Managed Services * Consulting * Product Supply & Support *
Tim MacKenzie The Fulcrum Group of Companies
System Architect Level 8, 628 Bourke Street
ph: +61-3-8601-6100 Melbourne VIC 3000 Australia
fx: +61-3-8601-6199 http://www.fulcrum.com.au/