Perl function to sort a file based on key fields

Hi,
I am new to PERL.I want to sort all the lines in a file based on 1,2 and 4th filelds.

Can U suggest me a command/function in perl for this operation..

Sorting data with perl is data type sensitive. Are you sorting numbers or text or what? You will still need to use the sort function but if you sort numbers you use the '<=>' operator, if you sort text or mixed data you will most likely use the "cmp" operator. Can you post some sample lines of data and explain how you want to sort them? Are all fields sorted in the same order (ascending/descending) or are some sorted one way and others sorted another way?

Or you can try and figure it out yourself:

http://perldoc.perl.org/functions/sort.html

The sample data looks like

/usr/apps|gen_run_script.ksh|#START|Jan 28th 01:16|/home/admin
/usr/apps|foreach_script.ksh|#START|Jan 28th 05:19|/home/admin
/usr/apps|splitting_files.ksh|#START|Jan 28th 09:10|/home/admin
.
.
.
.
. file contains hundreds of lines as shown

'|' is the delimiter..I want to sort each line of file based on 1,2 and 4th filed.only 4th filed is mixed(numeric,as it contains date)..

Can u tell the sort method in PERL..

Not having a year in the date makes it difficult to sort the data by date. The sort routine will assume they are all in the same year.

use strict;
use warnings;
use Time::Local;
open (IN, '<', 'c:/perl_test/testlog.txt') or die "$!";
my @sorted = map {$_->[0]}
             sort {$a->[1] cmp $b->[1] || $a->[2] cmp $a->[2] || epoch($a->[3]) <=> epoch($b->[3]) }
             map {chomp; [ $_,(split(/\|/))[0,1,3] ];} <IN>;
close (IN);
print "$_\n" for @sorted;


{
   my %months = (Jan=>0,Feb=>1,Mar=>2,Apr=>3,May=>4,Jun=>5,Jul=>6,Aug=>7,Sep=>8,Oct=>9,Nov=>10,Dec=>11);
   sub epoch {
      my ($date) = $_[0];
      my ($mon,$mday,$hour,$min) = split(/[\s:]/,$date);
      $mday =~ tr/a-zA-Z//d;
      return timegm(0,$min,$hour,$mday,$months{$mon},0);
   }
}

hi, not very clear about your requirement.

Anyway, pls try below and hope can help you some.

open FH,"<a.txt";
my @arr=<FH>;
sub usersort{
	my @t1=split(" ",$_[0]);
	my @t2=split(" ",$_[1]);
	my $a=sprintf("%s%s%s",$t1[0],$t1[1],$t1[3]);
	my $b=sprintf("%s%s%s",$t2[0],$t2[1],$t2[3]);
	return $a cmp $b;
}
print sort {usersort($a,$b)} @arr;

That will not sort the dates and could be very inefficient since it calculates the sort keys over and over. The use of the cached key sort (Schwartzian Transform) I posted avoids that problem although the epoch() function could potentially be called more than once for the same sort key.