perl 哈希按照 keys/values 排序
这里就用perl自带的DATA句柄做示例。
1 #!/usr/bin/perl 2 use strict; 3 use warnings; 4 5 my %hash; 6 my @arr; 7 while(<DATA>){ 8 chomp; 9 my @line = split /\s+/,$_; 10 $hash{$line[0].":".$line[1]} = $line[2]; 11 push @arr,%hash; 12 } 13 14 # sort hash by keys 15 foreach my $k(sort {$a cmp $b}keys %hash){ 16 print "$k\t$hash{$k}\n"; 17 } 18 19 print "*" x 50,"\n"; 20 21 # sort hash by values ; <=> for number, cmp for ascii 22 23 foreach my $k(sort {$hash{$a} <=> $hash{$b}} keys %hash){ 24 print "$k\t$hash{$k}\n"; 25 } 26 27 28 29 30 __DATA__ 31 chr1 1 10 32 chr1 100 2000 33 chr2 20 30 34 chr2 40 50 35 chr2 100 300 36 chr3 10 40 37 chr4 1000 1200
结果:
chr1:1 10
chr1:100 2000
chr2:100 300
chr2:20 30
chr2:40 50
chr3:10 40
chr4:1000 1200
**************************************************
chr1:1 10
chr2:20 30
chr3:10 40
chr2:40 50
chr2:100 300
chr4:1000 1200
chr1:100 2000
作者:天使不设防
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.