Perl script to sort data on second numeric field

Hi,

I'm a learner of PERL programming.

I've a input file with the below data:

SWAT_5, 1703, 2010-09-21
SWAT_6,  2345, 2010-09-21
SWAT_7,  1792, 2010-09-21
SWAT_8,  1662, 2010-09-21
SWAT_9,  1888, 2010-09-21
VXHARP_1,  171, 2010-09-21

I need to sort this data based on the second numeric field value and want to display only first two fields. Below is expected result:

VXHARP_1,  171
SWAT_8,  1662
SWAT_5,  1703
SWAT_7,  1792
SWAT_9,  1888
SWAT_6,  2345

I wrote the below script to accomplish this:

open( INFILE, "< $input_file") or die "cannot open input file $input_file: $!";
my @lines = <INFILE>;
close(INFILE);

@lines = sort @lines;

foreach my $line (@lines) {
  my @tokens = split(/,/, $line);
  my $id = $tokens[0];
  my $duration = $tokens[1];
  printf "$id, $duration\n";
}

But, I'm getting first field sorted output as below:

SWAT_5,  1703
SWAT_6,  2345
SWAT_7,  1792
SWAT_8,  1662
SWAT_9,  1888
VXHARP_1,  171

Please suggest me for my above code correction to sort based on second field.

Thanks and Regards / Mysore 101 Ganapati.

$ 
$ 
$ cat f8
SWAT_5, 1703, 2010-09-21
SWAT_6,  2345, 2010-09-21
SWAT_7,  1792, 2010-09-21
SWAT_8,  1662, 2010-09-21
SWAT_9,  1888, 2010-09-21
VXHARP_1,  171, 2010-09-21
$ 
$ 
$ perl -lne 'push @x, $_;
             END {@y = sort {(split ",", $a)[1] <=> (split ",", $b)[1]} @x;
                  print substr($_,0,rindex($_,",")) for @y
             }' f8
VXHARP_1,  171
SWAT_8,  1662
SWAT_5, 1703
SWAT_7,  1792
SWAT_9,  1888
SWAT_6,  2345
$ 
$ 

tyler_durden

print join "\n", map {$_->[1]} sort {$a->[0]<=>$b->[0]}map {my @tmp = split(",",$_); [$tmp[1],$tmp[0].",".$tmp[1]]} <DATA>;
__DATA__
SWAT_5, 1703, 2010-09-21
SWAT_6,  2345, 2010-09-21
SWAT_7,  1792, 2010-09-21
SWAT_8,  1662, 2010-09-21
SWAT_9,  1888, 2010-09-21
VXHARP_1,  171, 2010-09-21

by shell.

sort -t, -k2n infile |cut -d, -f1,2
ruby -F"," -ane 'BEGIN{h={}}; h[ [$F[0], $F[1]]] = $F[1].to_i ;END{  h.sort{|a,b| a[1]< = >b[1]}.each{|x| print "#{x[0].join(",")}\n"}  }' file 
perl -F"," -wlane '
push @a , [ $F[1]  , $_ ] ; 
END{ print  map {join(",",(split /,/,$_->[1])[0..1]),"\n"} sort {$a->[0]  <=> $b->[0] } @a  }
' infile.txt
o/p:-
VXHARP_1,  171
SWAT_8,  1662
SWAT_5, 1703
SWAT_7,  1792
SWAT_9,  1888
SWAT_6,  2345

Hi All

Thanks a lot for all your suggestions and I have implemented 'summer cherry's logic.
Also, I tried to understand his logic, but not able to do so.

Could any one explain the below logic. I mean I know map and sort function, but don't know, how exactly below line will execute.

With Regards,
Mysore Ganapati.