http://qs1969.pair.com?node_id=306592

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

I'm currently working on a wrapper script which needs to execute a script, and do the following:

Previously, the script was written in shell, and accomplished the first two requirements thusly:

( ( perl foo.pl | tee -a output.log ) 3>&1 1>&2 2>&3 3>&- | tee -a er +ror.log ) 3>&1 1>&2 2>&3 3>&-

However, capturing the return code of the script as well, even if it is possible, is beyond my script-fu.
Given that, and the fact that writing a wrapper to a Perl script in shell strikes me as inherently nasty, I set about recoding it in Perl.

The obvious solution seemed to be to redirect STDERR and STDOUT, and then set @ARGV and 'do' the script.
I could use IO::Tee to tee between STDOUT or STDERR, an IO::File object for the logfile, and an IO::String object for the variable store (to potentially be used in an email); and to assign the whole lot back to the relevant glob.
i.e. something like:

my ($output_cache, $error_cache); *STDOUT = multiplex( \*STDOUT, $output_cache, "$log_dir/output.$0" ); *STDERR = multiplex( \*STDERR, $error_cache, "$log_dir/errors.$0" ); do $script or die "Could not open '$script': $!" exit; sub multiplex { my ($handle, $cache, $log) = @_; my $cache_handle = IO::String->new( \$cache ); my $log_handle = IO::File->new( $log, 'w' ) or die "Could not open l +og file '$log': $!"; my $tee = IO::Tee->new( $handle, $cache_handle, $log_handle ); return $tee; }

However, this particular approach generates errors of the ilk 'print() on unopened filehandle STDOUT'.
I assume that assigning to globs only works with IO::File objects because they're blessed globrefs internally (though IO::Tee also uses Symbol::gensym in it's constructor, so perhaps I am wrong).

Another obvious approach is using 'select', which works fine for STDOUT, but not for STDERR.

So, my question boils down to two things:

Bear in mind that the script I'm wrapping ships with a proprietary software distribution, which we upgrade semi-regularly; so I want to avoid treating it as anything other than a black box, despite the fact that I can see the source.