位元詩人 技術雜談: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) 是資訊領域碩士,專注於從探索到產品的開發過程,並以工具驅動的方式改善專案。喜歡以開源專案作為成果,回饋社群。

主要方向包括:自用工具的打磨 (dogfooding)、編譯器前端在工具開發中的應用,以及將研究轉化為可維護的開源成果。

除了技術之外,也喜歡日本料理和黑咖啡,偶爾自助旅行,將生活中的靈感融入技術隨筆。