我想检查当前时间是否小,等于或大于20:00(例如)。 我怎么能用Perl做到这一点?
感谢。
答案 0 :(得分:3)
查看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()
而指出原始代码存在缺陷。
答案 1 :(得分:1)
目前还不清楚你在问什么,但也许是这样的。
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";
}
答案 2 :(得分:0)
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-别的逻辑。
答案 3 :(得分:0)
实际上正确的“if”条件会有所不同,如果小时大于分钟,你不需要检查分钟是否更大(我也修正了标志的方向:)。
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";
}