perl - Sorting hash keys by Alphanumeric sort -


i have read post sorting alphanumeric hash keys in perl?. starting perl, , don't understand clearly.

so have hash one:

  %hash = (         "chr1" => 1,         "chr2" => 3,         "chr19" => 14,         "chr22" => 1,         "x" => 2,     ) 

i'm trying obtain output this:

chr1 chr2 chr19 chr22 

but i'm obtaining output this:

chr1 chr19 chr2 chr22 

i have written code, creating above wrong output:

foreach $chr (sort {$a cmp $b} keys(%hash)) {     $total= $hash{$chr};     $differentpercent= ($differenthash{$chr} / $total)*100;     $round=(int($differentpercent*1000))/1000;     print "$chr\t$hash{$chr}\t$differenthash{$chr}\t$round\n"; } 

it prints:

chr1    342421    7449    2.175 chr10    227648    5327    2.34 chr11    220415    4468    2.027 chr12    213263    4578    2.146 chr13    172379    3518    2.04 chr14    143534    2883    2.008 chr15    126441    2588    2.046 chr16    138239    3596    2.601 chr17    122137    3232    2.646 chr18    130275    3252    2.496 chr19    99876    2836    2.839 chr2    366815    8123    2.214 

how can fix this?

update note @miller's comment below on shortcomings of sort::naturally module.

what asking relatively complicated sort splits each string alphabetical , numeric fields, , sorts letters lexically , numbers value.

the module sort::naturally ask, or can write this. appear have ignored x key, have sorted end using case-independent sort.

use strict; use warnings;  %hash = map { $_ => 1 } qw(     chr22  chr20  chr19  chr13  chr21  chr16  chr12  chr10  chr18     chr17  chry   chr5   chrx   chr8   chr14  chr6   chr3   chr9     chr1   chrm   chr11  chr2   chr7   chr4   chr15 );  @sorted_keys = sort {     @aa = $a =~ /^([a-za-z]+)(\d*)/;     @bb = $b =~ /^([a-za-z]+)(\d*)/;     lc $aa[0] cmp lc $bb[0] or $aa[1] <=> $bb[1]; } keys %hash;  print "$_\n" @sorted_keys; 

output

chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 chr17 chr18 chr19 chr20 chr21 chr22 chrm chrx chry 

using sort::naturally module (you have install it) write instead.

use strict; use warnings;  use sort::naturally;  %hash = map { $_ => 1 } qw(     chr22  chr20  chr19  chr13  chr21  chr16  chr12  chr10  chr18     chr17  chry   chr5   chrx   chr8   chr14  chr6   chr3   chr9     chr1   chrm   chr11  chr2   chr7   chr4   chr15 );  @sorted_keys = nsort keys %hash;  print "$_\n" @sorted_keys; 

the output identical above.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -