按值对哈希排序

时间:2021-04-23 16:04:31

标签: sorting perl

这不是我填充哈希的方式。为了方便阅读,这里是它的内容,键是一个固定长度的字符串:

my %country_hash = (
  "001 Sample Name   New Zealand" => "NEW ZEALAND",
  "002 Samp2 Nam2    Zimbabwe   " => "ZIMBABWE",
  "003 SSS NNN       Australia  " => "AUSTRALIA",
  "004 John Sample   Philippines" => "PHILIPPINES,
);

我想根据值获取排序的键。所以我的期望:

"003 SSS NNN       Australia  "
"001 Sample Name   New Zealand"
"004 John Sample   Philippines"
"002 Samp2 Nam2    Zimbabwe   "

我做了什么:

foreach my $line( sort {$country_hash{$a} <=> $country_hash{$b} or $a cmp $b} keys %country_hash ){
  print "$line\n";
}

还有; (我怀疑这会排序,但无论如何)

my @sorted = sort { $country_hash{$a} <=> $country_hash{$b} } keys %country_hash;
foreach my $line(@sorted){
  print "$line\n";
}

它们都没有正确排序。我希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:6)

如果您使用过 warnings,您会被告知 <=> 是错误的运算符;它用于数值比较。改用 cmp 进行字符串比较。请参阅sort

use warnings;
use strict;

my %country_hash = (
  "001 Sample Name   New Zealand" => "NEW ZEALAND",
  "002 Samp2 Nam2    Zimbabwe   " => "ZIMBABWE",
  "003 SSS NNN       Australia  " => "AUSTRALIA",
  "004 John Sample   Philippines" => "PHILIPPINES",
);

my @sorted = sort { $country_hash{$a} cmp $country_hash{$b} } keys %country_hash;
foreach my $line(@sorted){
    print "$line\n";
}

打印:

003 SSS NNN       Australia  
001 Sample Name   New Zealand
004 John Sample   Philippines
002 Samp2 Nam2    Zimbabwe   

这也有效(没有额外的数组):

foreach my $line (sort {$country_hash{$a} cmp $country_hash{$b}} keys %country_hash) {
    print "$line\n";
}
相关问题