Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^3: Close a file and reopen a new one at midnight

by clueless newbie (Chaplain)
on Jan 14, 2013 at 20:25 UTC ( #1013272=note: print w/replies, xml ) Need Help??

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 => '', 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;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1013272]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2017-08-17 06:34 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (282 votes). Check out past polls.