バッチスクリプトでは、何時〜何時の間だけ実行する/しない、といった制御が必要になる場合があります。この判定を簡単に行うための小さな Perl 関数です。Perl スクリプトの自動運転などで活躍するつもり。
#!/usr/bin/perl use strict; ### Schedule (From) <= T < (To) my %schedule = ( '21:00:00-27:00:00' => 1, '23:00:00-25:00:00' => 0, ); use Data::Dumper; print Dumper (%schedule); &testcase ('20:00:00'); &testcase ('21:00:00'); &testcase ('22:00:00'); &testcase ('22:59:59'); &testcase ('23:00:00'); &testcase ('24:00:00'); &testcase ('00:00:00'); &testcase ('00:59:59'); &testcase ('25:00:00'); &testcase ('01:00:00'); &testcase ('26:00:00'); &testcase ('02:00:00'); &testcase ('02:59:59'); &testcase ('03:00:00'); sub testcase { my ($item) = @_; printf "%s : %s ", $item, &isScheduledOn ($item) ? 'OK' : 'NG'; } ### sub isScheduledOn { my ($curtime) = @_; ;# return undef unless $curtime =~ m/s*(d+)s*:s*(d+)s*:s*(d+)s*/; my ($hc,$mc,$sc) = ($1,$2,$3); ;# my $ret = 0; foreach (keys %schedule) { my $switch = $schedule{$_}; ;# parse next unless m/s*(d+)s*:s*(d+)s*:s*(d+)s*-?s*(d+)s*:s*(d+)s*:s*(d+)s*/; my ($h1,$m1,$s1, $h2,$m2,$s2) = ($1,$2,$3, $4,$5,$6); ;# normalize; h:[00,23], m:[00,59], s:[00,59] ($m1++, $s1 -= 60) while 60 <= $s1; ($h1++, $m1 -= 60) while 60 <= $m1; ($h1 -= 24) while 24 <= $h1; ($m2++, $s2 -= 60) while 60 <= $s2; ($h2++, $m2 -= 60) while 60 <= $m2; ($h2 -= 24) while 24 <= $h2; ;# T1 must be < T2 ($h2 += 24) while _ti($h2,$m2,$s2) < _ti($h1,$m1,$s1); ;# Check on today and tomorrow my $_tic = _ti($hc,$mc,$sc); foreach (0..1) { if (_ti($h1,$m1,$s1) <= $_tic && $_tic < _ti($h2,$m2,$s2)) { return 0 unless $switch; $ret = 1; } $_tic += 24 * 60 * 60;# tomorrow } } return $ret; # sub _ti { ($_[0] * 60 + $_[1]) * 60 + $_[2] } }
X:temp>perl schedule.pl $VAR1 = { '21:00:00-27:00:00' => 1, '23:00:00-25:00:00' => 0 }; 20:00:00 : NG 21:00:00 : OK 22:00:00 : OK 22:59:59 : OK 23:00:00 : NG 24:00:00 : NG 00:00:00 : NG 00:59:59 : NG 25:00:00 : OK 01:00:00 : OK 26:00:00 : OK 02:00:00 : OK 02:59:59 : OK 03:00:00 : NG