Comparing times in perl without using modules
I am trying to compare two timestamps to see which one is the latest one, this would be easy if I could use the DateTime module, but unfortunately I do not have permissions to install any modules on the servers and therefore I am restricted to only native Perl commands.
T开发者_JS百科he times are in the form "MM/DD/YYYY hh:mm:ss".
If you first convert the times into YYYY/MM/dd hh:mm:ss
format using the code below:
my ($date, $time) = split(/\s+/, $val);
my ($m, $d, $y) = split(/\//, $date);
$val = sprintf("%04d/%02d/%02d %s", $y, $m, $d, $time);
You can then just use a standard lexical comparison on the dates.
You can use a regexp to reformat the date to "YYYY/MM/DD hh:mm:ss" format so that you can compare two dates directly.
$date =~ s|^(\d{2})/(\d{2})/(\d{4})|$3/$1/$2|;
The only part of the string that is out of order for a lexical sort is the YYYY
part, so you can compare that part separately.
# MM/DD/YYYY hh:mm:ss
# 0123456789T12345678
@sorted_dates = sort { substr($a,6,4) cmp substr($b,6,4) || $a cmp $b } @dates;
Perl includes Time::Piece and Time::Local modules. Or you can create executable with PAR::Packer that will include DateTime and copy it into server.
Of course, converting to "YYYY-MM-DD hh:mm:ss" format is easiest if any other features are not needed.
精彩评论