http://www.perlmonks.org?node_id=1013272


in reply to Re^2: Close a file and reopen a new one at midnight
in thread Close a file and reopen a new one at midnight

"compiled" but not tested!

Set the date of last write to "000000" and close and append to a new file when the date changes ie date of last write != today. Thus if nothing happens for a week no logs are created for those dead days.

#!/usr/bin/perl -w use strict; use IO::Socket; use MIME::Lite; my $nb_secs = 10; my $buf = ""; my $file; my $sock = new IO::Socket::INET( PeerAddr => '192.168.173.9', PeerPort => 4002, Proto => 'tcp', Type => SOCK_STREAM, ); die "cannot open socket" unless ($sock); my ($lastwrite,$today)="000000"; while ( my $line = <$sock> ) { if ( $lastwrite ne ($today=sprintf("%02d%02d%02d",(localtime())[5, +4,3]))) { # Close existing $file and reopen a new one at when the date c +hanges close $file; my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isd +st ) = localtime(time); my $ymd = sprintf( "%04d%02d%02d%02d%02d%02d", $year + 1900, $ +mon + 1, $mday, $hour, $min, $sec ); my $filename = "/tmp/$ymd.txt"; print $filename, "\n"; open $file, ">>","$filename" || die("Couldn't open $file"); $lastwrite=$today; } #Print current line to open $file. print $file $line; } close $file;