chris chris - 1 year ago 112
Perl Question

Perl: Sort Array after a Hash-value

Is there a "Perl-ish" way to sort a array of hashes after a hash-val?

my @l = ({k1 => "1", k2 => "one"}, {k1 => "2", k2 => "two"},
{k1 => "3", k2 => "three"});

foreach (@l)
print "\n" . $_->{k1} . ", " . $_->{k2};

The order I get is the order I inserted (what else...). But I'd like to sort it after a hash-value.
I can imagine the algorithmic-way. But I am asking about a maybe already existing function or something.


Answer Source

To sort by the value behind the k1 key, you can do as follows.

my @sorted = sort { $a->{k1} <=> $b->{k1} } @l;

The variables $a and $b are reserved special vars for sort. If your list-items are references, you can just use them as such.

Output with Data::Printer:

    [0] {
        k1   1,
        k2   "one"
    [1] {
        k1   2,
        k2   "two"
    [2] {
        k1   3,
        k2   "three"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download