Sorting 按值排序散列
这不是我填充哈希的方式。为了便于阅读,以下是其内容,键位于固定长度的字符串上:Sorting 按值排序散列,sorting,perl,Sorting,Perl,这不是我填充哈希的方式。为了便于阅读,以下是其内容,键位于固定长度的字符串上: my %country_hash = ( "001 Sample Name New Zealand" => "NEW ZEALAND", "002 Samp2 Nam2 Zimbabwe " => "ZIMBABWE", "003 SSS NNN Australia "
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";
}
foreach my$行(排序{$country_hash{$a}$country_hash{$b}或$a cmp$b}键%country_hash){
打印“$line\n”;
}
还有,;
(我怀疑这是否会解决问题,但无论如何)
my@sorted=sort{$country\u hash{$a}$country\u hash{$b}关键字%country\u hash;
foreach my$行(@sorted){
打印“$line\n”;
}
他们两个都没有正确排序。我希望有人能帮忙。如果你使用了
警告
,你会被告知
是错误的操作员;它用于数值比较。使用cmp
进行字符串比较。参考
这张照片是:
003 SSS NNN Australia
001 Sample Name New Zealand
004 John Sample Philippines
002 Samp2 Nam2 Zimbabwe
这也可以工作(没有额外的阵列):
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";
}