I want to check if current time is small , equal or great of 20:00 ( for example). How i can do it with Perl?
Thanks.
I want to check if current time is small , equal or great of 20:00 ( for example). How i can do it with Perl?
Thanks.
Check out the localtime
function.
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";
}
Update: Thanks, Dave Cross, for pointing out that the original code was flawed due to two calls to localtime()
.
It's not exactly clear what you're asking, but perhaps something like this.
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";
}
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";
}
It may be a little overkill for this situation, but the flexibility of DateTime allows you to easily implement other logic (different cutoffs weekday/weekend, cutoff at hour and minute) without needing to delve too much into the if-then-else logic.
Actually the correct "if" condition would be somewhat different, you don't need to check if minutes are greater if the hour is greater than the minutes(I also fixed the direction of the signs :)
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";
}