I think I have the right idea but there's some syntax/convention thing I'm messing up, because I get the error "Global symbol %timeHash requires explicit package name".
Code:
foreach $key (sort hashValueDescendingNum (keys(%timeHash))) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub hashValueDescendingNum {
my $hash = shift;
$hash{$b} <=> $hash{$a};
}
Inline
foreach my $key (sort { $timeHash{$b} <=> $timeHash{$a} } keys %timeHash) {
print "\t$key\t\t $timeHash{$key}\n";
}
Using a custom sort function the way you are trying to will not work well, because then your sub would need to access the original hash.
foreach my $key (sort hashValueDescendingNum (keys(%timeHash))) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub hashValueDescendingNum {
$timeHash{$b} <=> $timeHash{$a}; # Ew.
}
Instead you can abstract it further:
foreach my $key (sortedHashKeysByValueDescending(%timeHash)) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub sortedHashKeysByValueDescending {
my %hash = @_;
my @keys = sort { $hash{$b} <=> $hash{$a} } keys %hash;
return @keys;
}
The code is not efficient because it passes around the %hash though, references would be better:
foreach my $key (sortedHashKeysByValueDescending(\%timeHash)) {
print "\t$key\t\t $timeHash{$key}\n";
}
sub sortedHashKeysByValueDescending {
my $hash = shift;
return sort { $hash->{$b} <=> $hash->{$a} } keys %$hash;
}
use List::UtilsBy qw( rev_nsort_by );
foreach my $key ( rev_nsort_by { $timeHash{$_} } keys %timeHash ) {
...
}