Sunday, January 25, 2015

Sort by key fields Perl

#!/usr/bin/perl
use strict;
use warnings;
use 5.010;

my $file = 'matrixin.txt';
my @data;
open( FILE, $file ) or die "Can't open file '$file': $!";
while( ) {
chomp;
my @row = split;
push @data, \@row;
}
close( FILE );

my @sorted = sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } @data;  ##sort by col  2 then 3
#Print output
for my $i (0..$#sorted)
{
for my $j (0..$#{$sorted[0]})
{
   print "$sorted[$i][$j]","\t";
}
   print "\n";
}

No comments: