【问题标题】:Perl Date Comparison QueryPerl 日期比较查询
【发布时间】:2020-02-07 16:20:09
【问题描述】:

如果输入文件中提供的日期比使用 Perl 5.8.8 版的“今天”多一天,我正在尝试输出“不正常”。

当 test.txt 包含以下数据时,使用“./code.sh

07/02/2020 08/02/2020

当我重新散列下面的代码以尝试使用“今天的日期”作为变量时,输入文件中只有一个日期,我收到以下错误:

Use of uninitialized value in concatenation (.) or string at code.sh line 27, <> line 1

工作代码(输入文件中有两个日期):

#!/usr/bin/perl

use strict;
use warnings;

use Time::Piece;

#my $date = localtime->strftime('%d/%m/%Y');
#print "$date";

my $format = '%d/%m/%Y';

while (<>) {
   chomp;

         my ($str1, $str2) = split;
#        my ($date, $str2) = split;

#  my $dt1 = Time::Piece->strptime($date, $format);
   my $dt1 = Time::Piece->strptime($str1, $format);
   my $dt2 = Time::Piece->strptime($str2, $format);

   #  print "$date / $str2 ";
  print "$str1 / $str2 ";

     if ($dt2->julian_day - $dt1->julian_day ==1) {

         print "ok\n";

     } else {
         print "not ok\n";
         }
}

损坏的代码(输入文件中有一个日期):

#!/usr/bin/perl

use strict;
use warnings;

use Time::Piece;

my $date = localtime->strftime('%d/%m/%Y');
print "$date";

my $format = '%d/%m/%Y';

while (<>) {
   chomp;

#        my ($str1, $str2) = split;
         my ($date, $str2) = split;

   my $dt1 = Time::Piece->strptime($date, $format);
#  my $dt1 = Time::Piece->strptime($str1, $format);
   my $dt2 = Time::Piece->strptime($str2, $format);

     print "$date / $str2 ";
 # print "$str1 / $str2 ";

     if ($dt2->julian_day - $dt1->julian_day ==1) {

         print "ok\n";

     } else {
         print "not ok\n";
         }
}

不太清楚我做错了什么......

感谢任何帮助

【问题讨论】:

  • 这段代码有几个错别字。您的日期时间格式定义错误($d,您的意思是%d)并且您在Time::Piece 中错过了几次冒号。当我修复这些时,您的代码可以正常工作。

标签: perl date string-comparison


【解决方案1】:

键入代码时请多加注意,您的示例有一些错误类型

#!/usr/bin/perl
#
# vim: ai:ts=4:sw=4
#

use strict;
use warnings;
use feature 'say';

use Time::Piece;

my $format = '%d/%m/%Y';
my $date   = localtime->strftime($format);

say "Today is: $date\n";

my @str_dates = <DATA>;

chomp(@str_dates);

my $date1 = Time::Piece->strptime($str_dates[0], $format);
my $date2 = Time::Piece->strptime($str_dates[1], $format);

my $days_diff = $date2->julian_day - $date1->julian_day;

my $msg = ($days_diff == 1) ? "ok" :"not ok";

say "$date2 :: $date1 => $msg";
say "$date2 :: $date1 =  $days_diff day(s) apart";

__DATA__
07/02/2020
08/02/2020

输出

Today is: 07/02/2020

Sat Feb  8 00:00:00 2020 :: Fri Feb  7 00:00:00 2020 => ok
Sat Feb  8 00:00:00 2020 :: Fri Feb  7 00:00:00 2020 =  1 day(s) apart

注意:如果您使用,我会推荐:

vim 更好地使用选项:syntax on, ai,ts=4,sw=4

【讨论】:

  • 抱歉,我已经纠正了错字。我忘了提到我正在使用 Perl v5.8.8,没有升级系统的选项。我会更新问题以反映这一点。
猜你喜欢
  • 2013-09-16
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 2013-11-24
  • 2015-10-27
  • 2023-03-03
相关资源
最近更新 更多