二维哈希:使用$hash{$key1}{$key2} = $value;
遍历(注意加粗与加下划线的语句)
foreach my $key1 (sort keys %hash) #首先对key1进行排序
{
foreach my $key2 (sort {$hash{$key1}->{$b}<=>$hash{$key1}->{a}} keys %{$hash{$key1}}) #对value值按照数字大小进行逆序排序
# foreach my $key2 (sort {$a<=>$b} keys %{$hash{$key1}}) #对key2按照数字大小进行排序
{
print $key1." ".$key2." ".$hash{$key1}->{$key2}."
";
}
}
对比单维哈希
foreach my $key (sort{$hash{$b}<=>$hash{$a}} keys %hash)
{
print $key." ".$hash{$key}."
";
}
对比数组
方法一:@array2 = sort(@array)
方法二(遍历):
foreach my $a (sort @array){
print $a. " ";
}
哈希按value排序:
use
strict;
my %hash=('a'=>2,'b'=>3,'c'=>1);
foreach my $key (sort {$hash{$b} <=> $hash{$a}} keys %hash){
print $key,"=>",$hash{$key},"
";
}