View Full Version : hash problem and sorting
naqvia
09-12-2007, 11:05 PM
How would one sort based on the number of hash values of the keys in decreasing order. For example I have:
while (<puni>){
chomp;
my ($c_name,$locus,$size,$acc) = split;
$c_name =~s/\s+//;
$locus=~s/\s+//;
push @{$clones{$c_name}},"<font color=\"blue\">pUNI\($size\,$acc\)</font>";
$acc{$c_name} = $locus;
}
I want those keys in %clones that have multiple value elements to be printed out first and those keys that just have one value element printed lasted.
KevinADC
09-13-2007, 06:57 PM
sort the hash keys by the length of the arrays.
foreach my $keys (sort { scalar @{$clones{$b}} <=> scalar @{$clones{$a}} } keys %clones) {
print @{$clones{$keys}},"\n";
}
naqvia
09-13-2007, 09:58 PM
Now this is a bit more complicated. I make my hashes like this:
## retreive info from the files (gene,clone_name,locus,size,and accession num)
while (<puni>){
chomp;
my ($c_name,$locus,$size,$acc) = split;
$c_name =~s/\s+//;
$locus=~s/\s+//;
push @{$clones{$c_name}},"<font color=\"blue\">pUNI\($size\,$acc\)</font>";
$acc{$c_name} = $locus;
}
while (<sfi>){
chomp;
my ($c_name,$locus,$size,$acc) = split;
$c_name =~s/\s+//;
$locus=~s/\s+//;
my $c_name2 = "G".$c_name;
push @{$clones{$c_name}},"<font color=\"red\">pENTRsfi\($c_name2\,$acc\)</font>";
$acc{$c_name} = $locus;
# $siz
}
while (<topo>){
chomp;
my ($c_name,$locus,$size,$acc) = split;
$c_name =~s/\s+//;
$locus=~s/\s+//;
push @{$clones{$c_name}},"<font color=\"green\">pENTRtopo\($size\,$acc\)</font>";
$acc{$c_name} = $locus;
}
}
Now I want them sorted based on elements (like above), but I want to print those with pUNI and pENTRsfi first... before the others.
KevinADC
09-13-2007, 10:06 PM
Instead of push(), use unshift() for elements that you want to prepend to an array:
unshift @{$clones{$c_name}},"<font color=\"blue\">pUNI\($size\,$acc\)</font>";
naqvia
09-13-2007, 10:15 PM
doesnt work
KevinADC
09-14-2007, 07:18 PM
what else have you tried?
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.