我想使用Time::Piece
显示昨天的日期,并重载字符串化和算术运算,如下所示:
use strict;
use warnings;
use feature qw(say);
use Time::Piece;
use Time::Seconds;
say " Today is " . localtime;
say "Yesterday is " . localtime - ONE_DAY;
Today is Mon Sep 22 15:09:00 2014
Yesterday is Tue Dec 30 16:00:00 1969
然而,可以看出,今天的日期有效,但是昨天的时间已经过去了。
一种解决方案是在进行数学$today - ONE_DAY
之前创建一个变量。此外,以下替代格式显示了更多信息:
my $fmt = '%Y-%m-%d';
say "Yesterday is ", ( localtime - ONE_DAY )->strftime($fmt);
say "Yesterday is ", ( +localtime - ONE_DAY )->strftime($fmt);
say "Yesterday is ", ( scalar(localtime) - ONE_DAY )->strftime($fmt);
say "Yesterday is ", ( - ONE_DAY + localtime )->strftime($fmt);
Yesterday is 1969-12-30
Yesterday is 1969-12-30
Yesterday is 2014-09-21
Yesterday is 2014-09-21
上述第3和第4种方法可以正常工作。
那是什么交易?
答案 0 :(得分:6)
这可以使用B::Deparse
来诊断,以查看perl如何解释代码:
$ perl -MTime::Piece -MTime::Seconds -MO=Deparse -e '
print "Yest is " . localtime - ONE_DAY
'
print 'Yest is ' . localtime(-86400);
-e syntax OK
所以问题是localtime
将- ONE_DAY
视为其可选参数,而Minus operator -
正在切换到其一元上下文。
只需使用附加括号即可解决此问题:
use strict;
use warnings;
use feature qw(say);
use Time::Piece;
use Time::Seconds;
say "Today is " . localtime;
say " Yest is " . (localtime() - ONE_DAY);
Today is Mon Sep 22 16:25:45 2014
Yest is Sun Sep 21 16:25:45 2014