Can someone please tell me the best (most efficient) way for setting a night time period to be between 8:30pm and 7am and then detecting when the program in question is running at night time.
Do you mean: "How can a perl program detect that it is running between 8:30pm and 7am local time?" If that's the question, one answer would be a subroutine like the following. I've decided to set it up as a subroutine because that makes it easier to parameterize the conditions -- who knows, next week you might want a program to check whether it's running between 9:45am and 11:53am...
use POSIX;
sub timenow_is_between
{
my ( $bgn, $end ) = @_; # args are "HH:MM" strings (length==5)
# e.g. 20:30 or 07:00
my $timenow = strftime( "%H:%M", localtime );
if ( $bgn ge $end ) {
return ( $timenow ge $bgn or $timenow lt $end );
} else {
return ( $timenow ge $bgn and $timenow lt $end );
}
}
(Update: decided to use "ge" instead of "gt" when testing $bgn against $end, and when testing $timenow against $bgn; this should "do the right thing" in various boundary conditions, like $bgn and $end being identical, or different by just one minute.)
Here's an example of how you would use it:
if ( timenow_is_between( "20:30", "07:00" ) {
print "this program is running at night\n";
} else {
print "it is not night time right now\n";
}
But having seen the longer snippets of code you posted in a couple of your replies on this thread, it's not clear to me what your goal really is (and I wonder whether you have a clear idea of what your goal really is).
Note that POSIX (which provides the "strftime" function) is a "core" module -- it's available for use in any standard perl installation. |