当只有小时:分钟而不是像 YYYY-MM-DD HH:MM 这样的时间时,代码很棘手。这在当时可以被毫不含糊地解析。如果您可以更改记录器输出以提供完全限定的日期,那么您的工作会变得更加简单。下面的代码可以做到这一点。(免责声明:开始时间必须按时间顺序排列,否则有必要先对它们进行排序)。
(注意:对于此数据,我将时间分隔符从“-”更改为“\t”)
#!/usr/bin/perl
use strict;
use warnings;
use DateTime::Format::Strptime;
my $re = '(\S{10}\s\S{5})\t(\S{10}\s\S{5})$';
my $max;
my $parser = DateTime::Format::Strptime->new(pattern => '%F %H:%M');
while (<DATA>) {
chomp;
my ($start, $stop) = /$re/ or die $!;
$_ = $parser->parse_datetime($_) for $start, $stop;
# one time initialization of $max for first record
$max //= $start;
# when there are breaks in the continuity
$max = $start if $max < $start;
my $minutes = $stop <= $max ? 0 : $max->delta_ms($stop)->in_units('minutes');
printf "$_ %2d minutes\n", $minutes;
$max = $stop if $max < $stop; # stop is the new max if stop > max
}
__DATA__
Host A fails at 2012-07-03 14:15 2012-07-03 14:18
Host B fails at 2012-07-03 14:16 2012-07-03 14:21
Host C fails at 2012-07-03 14:17 2012-07-03 14:20
Host D fails at 2012-07-03 23:57 2012-07-04 00:05
Host E fails at 2012-07-03 23:58 2012-07-04 00:07
Host F fails at 2012-07-04 00:00 2012-07-04 00:08
Host G fails at 2012-07-04 00:01 2012-07-04 00:09
Host H fails at 2012-07-04 00:02 2012-07-04 00:08
Host I fails at 2012-07-04 14:17 2012-07-04 14:20
Host J fails at 2012-07-04 23:57 2012-07-04 23:59
Host K fails at 2012-07-05 00:00 2012-07-05 00:10
Host L fails at 2012-07-05 00:02 2012-07-05 00:09
Host M fails at 2012-07-05 00:02 2012-07-05 00:11
Host N fails at 2012-07-05 00:02 2012-07-05 00:10
它产生了以下输出:
Host A fails at 2012-07-03 14:15 2012-07-03 14:18 3 minutes
Host B fails at 2012-07-03 14:16 2012-07-03 14:21 3 minutes
Host C fails at 2012-07-03 14:17 2012-07-03 14:20 0 minutes
Host D fails at 2012-07-03 23:57 2012-07-04 00:05 8 minutes
Host E fails at 2012-07-03 23:58 2012-07-04 00:07 2 minutes
Host F fails at 2012-07-04 00:00 2012-07-04 00:08 1 minutes
Host G fails at 2012-07-04 00:01 2012-07-04 00:09 1 minutes
Host H fails at 2012-07-04 00:02 2012-07-04 00:08 0 minutes
Host I fails at 2012-07-04 14:17 2012-07-04 14:20 3 minutes
Host J fails at 2012-07-04 23:57 2012-07-04 23:59 2 minutes
Host K fails at 2012-07-05 00:00 2012-07-05 00:10 10 minutes
Host L fails at 2012-07-05 00:02 2012-07-05 00:09 0 minutes
Host M fails at 2012-07-05 00:02 2012-07-05 00:11 1 minutes
Host N fails at 2012-07-05 00:02 2012-07-05 00:10 0 minutes
希望这有帮助,
克里斯