Workshop in Computational Bioskills - sort_gene.pl

#!/usr/bin/perl -w
open (IN,"$ARGV[0]") || die "cannot open file\n";

while ($next = <IN>) {
  chomp $next;
  ($id,$length) = split (/\s+/, $next);
  $id2length{$id} = $length;  
}

close(IN);

@keys = keys( %id2length );
@sorted = sort {comp($a,$b)} @keys;

for ($k=0; $k <= $#sorted; $k++) {
  print_nice( $sorted[$k], $id2length{ $sorted[$k] });
} 

sub print_nice {
    print "gene: $_[0]\tlength: $_[1]\n";
}

sub comp {
  $a = shift;
  $b = shift;
  if ($id2length{$a} < $id2length{$b}) { return -1;}
  if ($id2length{$a} > $id2length{$b}) { return 1;}
  else { return ($a cmp $b ); }
}