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.
Thanks!
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"
}
]
@list = sort { $a->{'k1'} <=> $b->{'k1'} } @l;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.