Priyanka Tiwari
Priyanka Tiwari

Reputation: 35

Perl Sort date and time inside csv file

My file file.csv is having some columns among which column 1 represents date and time, I am trying to sort it by date and time but it is sorting only based on time. please check and suggest.

#!/usr/bin/perl

use strict;
my $input_dir = "d://perl//output";
my $output_dir = "d://perl//output";
my $input_file = "$input_dir//file.csv";
my $output_file = "$output_dir//output2_file.csv";
open (OUTPUT, ">>$output_file") or die "Error 016: Error creating $out
+put_file \n";
open (INPUT, "<$input_file") or die "Error 001: Error locating file $i
+nput_file \n";

my @array =(<INPUT>);

#print "Array\n";
#@print join( "\n", @array )."\n\n";

print "Sort Date\n";
print join( "\n", @sortedTime )."\n\n";

 print OUTPUT;
close (OUTPUT);
    close (INPUT);

data in file.csv looks like

2016-02-02:00:44,mttsmshub1  
2016-02-05:00:39,mttsmshub1  
2016-02-03:00:32,tttsmshub1  
2016-02-04:00:24,mttsmshub1  

current output looks like

2016-02-04:00:24,mttsmshub1  
2016-02-03:00:32,tttsmshub1  
2016-02-05:00:39,mttsmshub1  
2016-02-02:00:44,mttsmshub1  

expected output should be

2016-02-02:00:44,mttsmshub1  
2016-02-03:00:32,tttsmshub1  
2016-02-04:00:24,mttsmshub1  
2016-02-05:00:39,mttsmshub1  

Upvotes: 1

Views: 472

Answers (1)

elcaro
elcaro

Reputation: 2317

You do not actually use the sort operator in your code. Secondly, the print OUTPUT line makes no sense... You are printing nothing to the OUTPUT filehandle.

Simply, just sort as soon as you slurp your INPUT filehandle, then print it to your OUTPUT filehandle

my @array = sort <INPUT>;
print OUTPUT @array;

There should be no need to use join at all. The lines in your array already have newlines that were already there in the INPUT file.

Upvotes: 1

Related Questions