Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Perl Sort date and time inside csv file

by ukhare (Novice)
on Feb 11, 2016 at 07:06 UTC ( [id://1154919]=perlquestion: print w/replies, xml ) Need Help??

ukhare has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

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

Replies are listed 'Best First'.
Re: Perl Sort date and time inside csv file
by 2teez (Vicar) on Feb 11, 2016 at 09:50 UTC
    Hi ukhare,
    There is a number of things to point out in your code. Of course some of them are good practice while others are style and preference.
    1. You should also use warnings; in your codes
    2. As much as possible, try not to hard-core your file path in your program for portability issues. You might have to use the code some other places or some other time
    3. use open 3 arguments options. Instead of 2
    4. if you are using csv file, use Text::CSV or Text::CSV_XS module, instead of splitting or handpicking your data yourself.

    Now, to your data, just like hdb said you weren't sorting. Something like so should give what you expected, though you didn't show us that.
    use warnings; use strict; print sort grep $_ => <DATA>; __DATA__ 2016-02-02:00:44,mttsmshub1 2016-02-05:00:39,mttsmshub1 2016-02-03:00:32,tttsmshub1 2016-02-04:00:24,mttsmshub1

    Assumed Output:

    2016-02-02:00:44,mttsmshub1 2016-02-03:00:32,tttsmshub1 2016-02-04:00:24,mttsmshub1 2016-02-05:00:39,mttsmshub1
    Hope this helps.

    update:

    In the solution I have provided earlier, there is no need for the function grep, the code would still have worked without it. Thanks AnomalousMonk for pointing that out. ++ for you!! There

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me
      print sort grep $_ => <DATA>;

      I don't get the purpose of the grep on  $_ in the quoted statement. Is it intended to remove the blank  __DATA__ lines? It doesn't, and it seems to me that those lines in the OP were just an artifact of failure to use  <code> tags in the first place. Can you please explain further?


      Give a man a fish:  <%-{-{-{-<

Re: Perl Sort date and time inside csv file
by Discipulus (Canon) on Feb 11, 2016 at 08:34 UTC
    wellcome ukhare,

    I've modified a bit your input file (to contain unordered dates) as follow

    #cat unsorteddates.csv 2016-02-05:00:39,mttsmshub1 2005-02-02:00:44,mttsmshub1 2012-02-03:00:32,tttsmshub1 2013-02-04:00:24,mttsmshub1 2000-04-02:00:44,mttsmshub1

    For your convenience you can convert your dates to epoch times using, for example, Date::Parse ( but see Re: Date to epoch ) after having chomped strings from file and having splitted their content. You'll feed with this map block the @unsorted array with anonymous arrays containing as 0th element the epoch and as 1st one the other string untouched.

    The resulting datastructure will be:

    ( [1454629140, "mttsmshub1"], [1107301440, "mttsmshub1"], [1328225520, "tttsmshub1"], [1359933840, "mttsmshub1"], [954629040, "mttsmshub1"], )

    Then in a second block you sort by the 0th field of each anonymous array of @unsorted (ie epochs) but before printing you reconvert back epochs to strings (i've used scalar localtime ($$_[0]) for lazyness: choose the appropriate format)

    use strict; use warnings; use Date::Parse; open my $csv,'<','unsorteddates.csv' or die "Unable to open for read"; my @unsorted = map { chomp; my @parts = split ',',$_; [ str2time($parts[0]),$parts[1] ] } <$csv>; print join "\n", map {scalar localtime ($$_[0]).",$$_[1]"} sort {$$a[0] <=> $$b[0]} @unsorted; # output Sun Apr 2 00:44:00 2000,mttsmshub1 Wed Feb 2 00:44:00 2005,mttsmshub1 Fri Feb 3 00:32:00 2012,tttsmshub1 Mon Feb 4 00:24:00 2013,mttsmshub1 Fri Feb 5 00:39:00 2016,mttsmshub1

    HtH

    L*

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Perl Sort date and time inside csv file
by hdb (Monsignor) on Feb 11, 2016 at 07:50 UTC

    Well, at a glance, it looks like your data is already sorted by time (descending). You do not do any sorting, so what do you expect?

Re: Perl Sort date and time inside csv file
by Laurent_R (Canon) on Feb 11, 2016 at 11:15 UTC
    I might be blind, but I can't see where you're doing the actual sort, nor can I see where the @sortedTime array is declared and populated.

    If you had included use warnings;, you would probably obtain a warning about the @sortedTime array not being initialized, which might have given you a clue about missing code.

      THANKS !! CHEERS

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1154919]
Approved by hdb
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-03-29 12:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found