perl - Sort hash attending to two parameters -
i have hash keys in following format:
scaffold_902_159 scaffold_2_1980420 scaffold_2_10 scaffold_10_402
i want print out hash sorted in following format:
scaffold_2_10 scaffold_2_1980420 scaffold_10_402 scaffold_902_159
so first have order numerically attending first number , attending last one. don't want regular expression searching "scaffold_" since may vary. mean, can have hash other format "blablabla_number_number, or blablablanumber_number". last part of key _number, thing permanent.
i've code sorts numerically attending first number:
my @keys = sort { ($aa) = $a =~ /(\d+)/; ($bb) = $b =~ /(\d+)/; $aa <=> $bb; } keys %hash; foreach $key (@keys) { print $key; }
any suggestion?
sort::naturally rescue!
#!/usr/bin/perl use strict; use warnings; use sort::naturally qw(nsort); %hash = ( scaffold_902_159 => 'v1', scaffold_2_1980420 => 'v2', scaffold_2_10 => 'v3', scaffold_10_402 => 'v4', ); print "$_\n" nsort keys %hash;
output:
scaffold_2_10 scaffold_2_1980420 scaffold_10_402 scaffold_902_159
as per query, tried out keys did not have number in middle.
#!/usr/bin/perl use strict; use warnings; use sort::naturally qw(nsort); @keys = qw( should_come_last_9999_0 blablabla_10_403 scaffold_902_159 scaffold_2_1980420 scaffold_2_10 scaffold_10_402 blablabla902_1 blablabla901_3 ); print "$_\n" nsort @keys;
output:
blablabla_10_403 blablabla901_3 blablabla902_1 scaffold_2_10 scaffold_2_1980420 scaffold_10_402 scaffold_902_159 should_come_last_9999_0
Comments
Post a Comment