sorting - How do I sort a perl hash by multiple keys? -
hi have data structure of following form:
$data = { 'a' => { key1 => 2, key2 => 1 }, 'b' => { key1 => 1, key2 => 2 }, 'c' => { key1 => 1, key2 => 1 }, 'd' => { key1 => 3, key2 => 2 }, 'e' => { key1 => 3, key2 => 1 }, 'f' => { key1 => 1, key2 => 2 }, };
what want able loop through data structure in ascending order of key2
, descending order of key1
, , ascending order of hash key, e.g:
e c d b f
how can achieve in perl? know can sort hash key using sort keys %$data
, how can sort multiple values , keys?
a similar question has been asked before , can found here: sorting array of hash multiple keys perl
basically, perl has 2 operators sorting, <=>
, cmp
return -1, 0 or 1, depending on if left hand side less than, equal to, or greater right hand side. <=>
used numerical comparison, , cmp
used stringwise comparison. more detail use can found here: equality operators.
these operators can used perl's sort
function , in conjuction or
operator can used achieve result you're after:
#!/usr/bin/perl use strict; use warnings; $data = { 'a' => { key1 => 2, key2 => 1 }, 'b' => { key1 => 1, key2 => 2 }, 'c' => { key1 => 1, key2 => 1 }, 'd' => { key1 => 3, key2 => 2 }, 'e' => { key1 => 3, key2 => 1 }, 'f' => { key1 => 1, key2 => 2 }, }; @sorted = sort { $data->{$a}->{key2} <=> $data->{$b}->{key2} or $data->{$b}->{key1} <=> $data->{$a}->{key1} or $a cmp $b } keys %{$data}; $key (@sorted){ print "$key\n"; }
since <=>
, cmp
return 0 (false) equality, means can chain equality checks or
or ||
.
in example above $a
, $b
refer key of $data
hashref @ particular iteration of sort. using these keys can access particular values of hash, e.g. $data->{$a}->{key2}
. putting $a
before $b
cause sort in ascending order, , putting $b
before $a
cause sort in descending order.
Comments
Post a Comment