carsonholt has asked for the wisdom of the Perl Monks concerning the following question:

I have a strange error that occurs in code I wrote. I'm trying to redirect STDOUT and STDERR to a log file. When I run the program, sometimes it works and sometimes I continue to get STDOUT to the screen in addition to the log file. I don't change the code. I just re-run the program and I get different results each time. Here's how I redirected the output. If someone knows why this would be happening, please let me know.

warn "QUIET MODE: Program operations and errors are being redirected t +o the file arbol.log\n"; close (STDERR); open (STDERR, "> ".$outpath."/arbol.log"); open (NEW_OUT, ">&STDOUT"); open (STDOUT, ">&STDERR");

Replies are listed 'Best First'.
Re: Redirecting output
by almut (Canon) on Jul 18, 2007 at 21:37 UTC

    You might want to check if the open statements are sometimes failing (for whatever reason - you never know...). In that case, printing $! might give you some clue.

Re: Redirecting output
by carsonholt (Initiate) on Jul 18, 2007 at 21:38 UTC
    Error solved. The directory $outpath was not being created but was created later in my code, so STDERR did not always get redirected. STDOUT was then not redirected because STDERR is now a closed file handle.
      And that just goes to show the value of checking open for errors...

      open ... or die "couldn't open XYZ: $!";
Re: Redirecting output
by Akoya (Scribe) on Jul 18, 2007 at 21:26 UTC
    I noticed that you close and reopen STDERR, but don't close STDOUT before you open it. That could possibly be the problem. Try:
    close STDERR; close STDOUT; open STDERR, '>', "$outpath/arbol.log"; open STDOUT, ">&STDERR";
Re: Redirecting output
by wojtyk (Friar) on Jul 18, 2007 at 21:28 UTC
    It may be a buffering problem as well. Consider using hot piping.
    select(STDERR); $| = 1; select(STDOUT); $| = 1;

      What suggests to you that it might be a buffering problem?