我想检查当前时间是否小于、等于或大于 20:00(例如)。我怎么能用 Perl 做到这一点?
谢谢。
查看localtime
功能。
use warnings;
use strict;
my $after_time = "13:32";
my @time = localtime(time);
if ($after_time =~ /(\d+):(\d+)/ and
$time[2] >= $1 and
$time[1] >= $2
)
{
print "It is after $after_time";
}
更新:感谢 Dave Cross 指出由于两次调用localtime()
.
目前还不清楚你在问什么,但也许是这样的。
use Time::Piece;
my $hour = localtime->hour;
if ($hour < 20) {
say "It's before 20:00";
} elsif {$hour > 20) {
say "It's after 20:00";
} else {
say "It's 20:00";
}
实际上正确的“如果”条件会有所不同,如果小时大于分钟,您不需要检查分钟是否更大(我还固定了标志的方向:)
use warnings;
use strict;
my $after_time = "13:32";
my @time = localtime(time);
if ( $after_time =~ /(\d+):(\d+)/
and (( $time[2] > $1 ) || ( $time[2] == $1 and $time[1] >= $2 ))
) {
print "It is after $after_time";
}
my $now = DateTime->now(time_zone => 'local');
my $cutoff = $now->clone->truncate( to => 'day' )->set(hour => 20);
if ($now < $cutoff) {
say "It's before 20:00";
} elsif ($now > $cutoff) {
say "It's after 20:00";
} else {
say "It's exactly 20:00";
}
对于这种情况可能有点矫枉过正,但 DateTime 的灵活性允许您轻松实现其他逻辑(工作日/周末的不同截止时间,小时和分钟的截止时间),而无需深入研究 if-then-else 逻辑。