简体   繁体   中英

How to sort an hash Reference in perl by descending/ascending values and ascending/descending keys?

my hash reference to an hash looks something like this

my %hey = (
    144 => 'Abc_test1',
    25  => 'sample2',
    114 => 'User',
    145 => 'abc_test2',
);

I want output order as

Abc_test1  
User
abc_test2
sample2

which I should be able to store in some variable

Any help?

Sort is using an expression to work out what order to sort things in, so it's not limited to just comparing one thing. In your case you want something like this...

my @sorted_values = map $hey{$_}, sort {$hey{$b} cmp $hey{$a} or $a <=> $b} keys %hey;

It firstly compares the values of the hash and sorts them in descending order. In the case where the two values are identical, it then compares the key values and sorts in ascending order.

values=[sort {$a<=>$b and $hey->{$a} cmp $hey->{$b}} keys  %$hey],

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM