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

Hello esteemed monks. Two questions about using Time::Piece which I've not been able to understand from the documentation page.

I have a number of date/time strings I want to sort and compare to localtime.

use Time::Piece; use Time::Seconds; use strict; my $dateformat = "%H:%M:%S, %m/%d/%Y"; my $date1 = "11:56:41, 09/14/2022"; my $date2 = "11:22:41, 09/16/2022"; my $date3 = "11:20:41, 09/13/2022"; $date1 = Time::Piece->strptime($date1, $dateformat); $date2 = Time::Piece->strptime($date2, $dateformat); $date3 = Time::Piece->strptime($date3, $dateformat); my(@ds) = ($date1,$date2,$date3); my(@sorted) = sort(@ds); foreach my $dt (@sorted){ print $dt, $/; }

This results in:

Fri Sep 16 11:22:41 2022 Tue Sep 13 11:20:41 2022 Wed Sep 14 11:56:41 2022

Question 1: why is it sorting the future date at the top of the list?

Question 2: is using Time::Piece->(strptime) the best way to create objects for each of my variables? I didn't see any other way to do that in the doc.

Thank you for any help.

Replies are listed 'Best First'.
Re: Time::Piece puzzlement
by hippo (Archbishop) on Sep 15, 2022 at 17:51 UTC
    Question 1: why is it sorting the future date at the top of the list?

    Because you are sorting lexically and F comes before T and W.

    use strict; use warnings; use Time::Piece; use Time::Seconds; my $dateformat = "%H:%M:%S, %m/%d/%Y"; my $date1 = "11:56:41, 09/14/2022"; my $date2 = "11:22:41, 09/16/2022"; my $date3 = "11:20:41, 09/13/2022"; $date1 = Time::Piece->strptime($date1, $dateformat); $date2 = Time::Piece->strptime($date2, $dateformat); $date3 = Time::Piece->strptime($date3, $dateformat); my(@ds) = ($date1,$date2,$date3); my(@sorted) = sort(@ds); print "Lexically\n"; foreach my $dt (@sorted){ print $dt, $/; } @sorted = sort { $a->epoch <=> $b->epoch } @ds; print "\nTemporally\n"; foreach my $dt (@sorted){ print $dt, $/; }
    Question 2: is using Time::Piece->(strptime) the best way to create objects for each of my variables? I didn't see any other way to do that in the doc.

    Yes, it probably is the best way. Note that you could use arrays throughout instead of $date1, $date2, $date3, etc.


    🦛

      aha of course! thank you.