No, you don't, you Stoner :-) But finding out wether a time in between a given interval or not is easy. Doing it this way saves you from having to deal with fixed switch times, which are, as you wrote, unreliable in case of outages or just the computer being shut down at the wrong moment.
use 5.24.1;
use feature qw:signatures:;
no warnings qw:experimental:;
my @off_from = (22, 0, 0); #22:00:00
my @off_until = (08, 0, 1); #08:00:00
sub cmpt ( $a, $b ) {
for ( 0 .. 2 ){
return $a->[$_] <=> $b->[$_] if $a->[$_] != $b->[$_] ;
}
return 0;
}
sub is_nighttime( $now )
{
my @now = @{$now} || (localtime(time))[2,1,0];
if ( cmpt( \@off_from, \@off_until ) == 1 ) { # over midnight
return cmpt(\@now, \@off_from) == 1 || cmpt( \@now, \@off_unti
+l ) == -1;
}
else { # all same day
return cmpt(\@now, \@off_from) == 1 && cmpt( \@now, \@off_unti
+l ) == -1;
}
return 0;
}
Edit: Removed C&P remnant
Edit: added code
Edit: added <=> (it's been a while)
holli
You can lead your users to water, but alas, you cannot drown them.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.