I am very new to perl. I am working on a script that runs everyday. I want to check that current time is less than a specific time. My current solution is that I extract hour
and min
from localtime
and then compare it. But I was told to find a better solution.
Current code:
my $flag;
for (;;) {
$flag = GetValue();
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
if( $flag ) {
#do action here
last;
} elsif ( $hour <= 17 ) {
if( $min <=30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
} else {
die "Error";
}
} else {
die "Error";
}
}
Basically, the statement $flag = GetValue();
sometimes returns undefined value unexpectedly and causes the script to fail. So we want to check if $flag defined. If it is defined then we execute some code and exit the for loop. Else we check the time. If the time is less that 17:30 then we want to wait for some time and try to get the value of flag again. I only need to change the logic of comparing current time to 17:30
I want my something like:
} elsif ( $current_time <= 17:30 ) {
print STDOUT "Keep running till 17:30 \n";
sleep 300;
}
How do I achieve this?
CodePudding user response:
The good and solid way to deal with date-times is to use a good library, like DateTime
my $dt_mark = DateTime
-> now(time_zone => 'local')
-> set(hour => 17, minute => 30);
for (;;) {
...
elsif ( DateTime->now(time_zone => 'local') <= $dt_mark ) {
...
One can avoid constructing a new object for every comparison but that would make the code more complicated. Note that DateTime
is a large library and this could be an overkill.
If the purpose is indeed to merely compare the current time to a fixed hour-minute then perhaps
elsif ( $hour < 17 or ($hour == 17 and $min <= 30) )
is good enough?
Or form and use strings that can be lexically compared
elsif ( sprintf("dd", $hour, $min) lt '1730' )