如何迭代地比较数组值中的时间戳

时间:2015-07-30 11:54:26

标签: perl

我有一个数组

@array = ( 'Apr 11 21:14:25',
           'Apr 11 21:10:10',
           'Apr 11 21:09:10',
           'Apr 11 21:07:10',
         );

在这里,我想在数组中记录时间戳 处理:  数组中的第一个值应与第二个值进行比较,以检查2分钟的时差?  数组中的第二个值应与第三个值进行比较,并再次检查2分钟的时差。  同样的过程应该继续

关于如何在perl中实现这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

我们不会在没有您先付出努力的情况下发出答案。但它是午餐时间,我想要一个简单的编程问题。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my @times = (
  'Apr 11 21:14:25',
  'Apr 11 21:10:10',
  'Apr 11 21:09:10',
  'Apr 11 21:07:10',
);

# Need a year for this to make sense. Let's use
# the current one.
my $year = localtime->year;

# Convert the string dates to Time::Piece objects
my @timepieces = map {
  Time::Piece->strptime("$year $_", '%Y %b %d %H:%M:%S')
} @times;

for (1 .. $#times) {
  say "Comparing $times[$_ - 1] with $times[$_]";
  # Use abs() so we don't care which is larger.
  my $seconds = abs($timepieces[$_ - 1] - $timepieces[$_]);

  if ($seconds == 120) {
    say 'Exactly two minutes difference';
  } elsif ($seconds > 120) {
    say 'More than two minutes difference';
  } else {
    say 'Less than two minutes difference';
  }
}