美思 技術雜談: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.
關於作者

身為資訊領域碩士,美思認為開發應用程式的目的是為社會帶來價值。如果在這個過程中該軟體能成為永續經營的項目,那就是開發者和使用者雙贏的局面。

美思喜歡用開源技術來解決各式各樣的問題,但必要時對專有技術也不排斥。閒暇之餘,美思將所學寫成文章,放在這個網站上和大家分享。