技術雜談:Sort by Hash Values in Perl

PUBLISHED ON AUG 25, 2014

    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;
        }
    }

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