位元詩人 技術雜談:Sort by Hash Values in Perl

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

Since hash is a one-way relation, you cannot directly sort by hash values and get hash keys in Perl. However, by customized sort subroutine, you can also sort by hash values. This post shows the trick.

You still need hash keys for later use, so we sort hash keys here. The catch is in the by_value subroutine. Here we pass $a and $b to the subroutine and compare them by the hash value.


# assume a pre-defined %hash
my @sorted_keys = sort { by_value($a, $b) } keys %hash;

sub by_value {
    my ($a, $b) = @_;
    my $value = $hash{$a} cmp $hash{$b};

    if ($value == 0) {
        return $a cmp $b;
    }
    else {
        return $value;
    }
}
{{< / highlight >}}

This subroutine must be placed after the hash declaration, or Perl will not know which hash you want to sort.
關於作者

位元詩人 (ByteBard) 是資訊領域碩士,喜歡用開源技術來解決各式各樣的問題。這類技術跨平台、重用性高、技術生命長。

除了開源技術以外,位元詩人喜歡日本料理和黑咖啡,會一些日文,有時會自助旅行。