Amruta
Amruta

Reputation: 1575

Perl: compare current time to a specific time to

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?

Upvotes: 2

Views: 395

Answers (1)

zdim
zdim

Reputation: 66881

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("%02d%02d", $hour, $min) lt '1730' )

For the stated purpose it is fine to do

my (undef, $min, $hour) = localtime(time);

This may be clearer as well as it directly indicates which parts of localtime's return are used.

Can also leave out time, per localtime

localtime EXPR
localtime
...
If EXPR is omitted, localtime uses the current time (as returned by time).

Upvotes: 3

Related Questions