[kw-pm] Sorting Question

Matt Sergeant matt at sergeant.org
Thu Mar 10 11:07:40 PST 2011


Robert Pike wrote:
> What's the most efficient way to loop through a hash while sorting on it's values (as opposed to it's keys)? The values of the hash are (for arguments sake) "Person's name#Number assigned" (i.e. Tom Smith~101012). The names are variable length and I don't want anything including and after the tilde to be included in the sort (i.e. just the name strings). Any suggestions? Thanks.
Depends on the size of the hash, but if it's likely to be large then you 
probably want a schwarzian transform.

Basically that would be:

# given %hash
for my $key ( map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { (my 
$val_no_tilde = $hash{$_}) =~ s/~.*//; [$_, $val_no_tilde] } keys %hash ) {
    # do something with $key
}

Breaking that down, how it works (read it right to left) is it creates a 
list of arrayrefs containing [ key, value-without-tilde-stuff ], then 
sorts on that, then pulls out just the key at the end.

(I didn't test the code - may have typo'd)

Matt.


More information about the kw-pm mailing list