Perl Capture and Modify STDERR before it prints to a file

Posted by MicrobicTiger on Stack Overflow See other posts from Stack Overflow or by MicrobicTiger
Published on 2013-07-02T22:43:36Z Indexed on 2013/07/03 5:05 UTC
Read the original article Hit count: 159

Filed under:
|
|
|
|

I have a perl script which performs multiple external commands and prints the outputs from STDERR and STDOUT to a logfile along with a series of my own print statements to act as documentation on the process.

My problem is that the STDERR repeats ~identical prints as example below. I'd like to capture this before it prints and replace with the final result for each of the commands i run.

blocks evaluated : 0
blocks evaluated : 10000
blocks evaluated : 20000
blocks evaluated : 30000
...
blocks evaluated : 3420000
blocks evaluated : 3428776

Here's how I'm getting STDOUT and STDERR

my $logfile = "Logfile.log";     #log file name
#--- Open log file for append if specified ---
if ( $logfile ) 
  {
    open ( OLDOUT, ">&", STDOUT )  or die "ERROR: Can't backup STDOUT location.\n";
    close STDOUT;
    open ( STDOUT, ">", $logfile ) or die "ERROR: Logfile [$logfile] cannot be opened.\n"; 
  }

if ( $logfile ) 
  { 
    open ( OLDERR, ">&", STDERR ) or die "ERROR: Can't backup STDERR location.\n";
    close STDERR;
    open ( STDERR, '>&STDOUT'   ) or die "ERROR: failed to pass STDERR to STDOUT.\n";
  }

and closing them

close STDERR;  
open ( STDERR, ">&", OLDERR ) or die "ERROR: Can't fix that first thing you broke!\n";
close STDOUT; 
open ( STDOUT, ">&", OLDOUT ) or die "ERROR: Can't fix that other thing you broke!\n";   

How do I access the STDERR when each print is occurring to do the replace? Or prevent it from printing if it isn't the last of the batch.

Many Thanks in advance.

© Stack Overflow or respective owner

Related posts about perl

Related posts about redirect