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

posted @ 2022-03-03 22:32  天使不设防  阅读(267)  评论(0编辑  收藏  举报