通过值对哈希表排序

3
这不是我填充哈希表的方式。为了更加易读,这里是它的内容。其中,键位于一个固定长度的字符串上:
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个回答

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";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接