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

Nick Hilliard nick at netability.ie
Thu May 6 03:38:34 CDT 2004


There is a certain code clarity / readability / simplicity to using
FileCache, though:

use FileCache;

while (1) {
	my $date = blah blah;
	my $log = cacheout "$date.log";

	blah blah blah;
}

Nick


> 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.





More information about the Dublin-pm mailing list