in reply to writing to logfile in a loop

Observe the following code:

use IO::Handle; use strict; $|=1; my $io=new IO::Handle; open LOG,">> mylofile.txt" or die "mylogfile.txt: $!"; $io->fdopen(fileno(LOG),"w+") or die $!; $io->autoflush(1); my $foo=0; while(1){ $foo++; printf "Iteration: %d\n",$foo; $io->printf("Looped in %d\n",$foo); sleep 2; }

I normally don't do Windows, but since I had a VMWare session going I fired up a quick test of your problem. Ran the above code and killed it with the Task Manager and no data was harmed in the making of rhis node. (Everything I expected was in the log file!)


Peter L. Berghold -- Unix Professional
Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

Replies are listed 'Best First'.
Re^2: writing to logfile in a loop
by ikegami (Patriarch) on Nov 21, 2006 at 21:07 UTC

    That's needlessly complicated. LOG and $io? autoflush and other IO::Handle methods can be used on any file handle, including barewords. That means that only LOG is needed. Or better yet, a lexical var ($log).

    use strict; use warnings; use IO::Handle; my $log_file = 'mylogfile.txt'; open my $log, '>>', $log_file or die "Unable to open log file \"$log_file\": $!\n"; STDOUT->autoflush(1); $log->autoflush(1); my $foo=0; while(1){ $foo++; printf "Iteration: %d\n",$foo; $log->printf("Looped in %d\n",$foo); # or printf $log ... sleep 2; }

    I also

    • improved the error message,
    • used the safer 3-arg open,
    • made the log file name easily editable, and
    • avoided the cryptic $|.

      Actually, I tried just that prior to my post. It errored out on me. Possibly the version of Perl that was installed on my VMWare virtual machine is at fault. At any rate if it works for you, use it. If not, my solution is just as valid.

      Not sure I understand your comment about $| being cryptic. Seems like Perl 101 to me...


      Peter L. Berghold -- Unix Professional
      Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg

        I tried just that prior to my post. It errored out on me.

        Did you have IO::Handle loaded? Like I said earlier, IO::Handle needs to be loaded (even though $log isn't an IO::Handle).

        It works at least since 5.6.1.

        Not sure I understand your comment about $| being cryptic. Seems like Perl 101 to me...

        STDOUT->autoflush(1); is more accessible than $| = 1.