[Dub-pm] Time::Piece && while loops

John Tobin tobinjt at netsoc.tcd.ie
Wed May 5 17:50:15 CDT 2004


On Wed, May 05, 2004 at 09:51:31PM +0100, Andrew Barnes wrote:
> SOooo... when talking to Doc on IRC last night we discussed using a while
> loop to do this.  My catch is trying to work out the "best way"
> (programatically, as well as "resource-wise") to do this - ie. check the
> day, and while $date != $date + 1, write into the log file - otherwise,
> update $date, $logfile, and write into the new file

How about alarm?  Something like this, cleaned up a bit, should do it:

while ( 1 ) {
	my $date = blah blah;
	my $logfile = File::Spec::catfile $logdir, "$date.log";
	my $log = new IO::File ">> $logfile"
		or die "$0: failed to open $logfile\: $!\n";
	my $seconds = time;
	my $day = 60 * 60 * 24;
	# the number of seconds between now and midnight
	my $midnight = $day - ( $seconds % $day );
	# paranoia: alarm 0 means cancel the alarm, meaning we'll never
	# be woken up, so sleep for a second to get around that - it'll
	# get us past midnight.
	if ( $midnight == 0 ) {
		sleep 1;
		next;
	}
	eval {
		local $SIG{ALRM} = sub {
			die "it's midnight";
		};
		alarm $midnight;
		while ( <$input> ) {
			print $log $_
				or die "$0: failed writing to ",
					"$logfile\: $!\n";
			undef $_;
		}
		alarm 0;
		# we've reached eof, so exit the loop?
		last;
	};
	# die for real if we couldn't write to the logfile
	if ( defined $@ and $@ =~ m/failed writing to/ ) {
		die $@;
	}
	if ( defined $_ ) {
		# We were interrupted between reading the next line and
		# undef $_; write the current line to the log, just in
		# case.  We may get it logged twice, but that's probably
		# better than not getting it logged at all.
		print $log $_
			or die "$0: failed writing to $logfile\: $!\n";
	}
}

You may end up with a line logged twice; I don't know how important it
is that it shouldn't happen.  If it's really important, you could play
games blocking signals, but that leaves you with the problem of the
signal not waking you up in time.  Tricky.

-- 
John Tobin
"It's not that I disagree with Bush's economic policy, or his foreign
policy, it's that I believe he's a child of Satan here to destroy the
planet earth."                                            -- Bill Hicks



More information about the Dublin-pm mailing list