|go ahead... be a heretic|
Re: Best Way to Redirect STDERR to a Scalarby davido (Archbishop)
|on Sep 13, 2003 at 22:35 UTC||Need Help??|
The first method I would propose is based on a technique I read in the Perl 5.8.0 perldoc perlfunc manpage for open. The trick discussed therein is to close the old STDERR before reopening it, redirected to a scalar.
I'm sorry to say that this proposed method works only under 5.8.0 or later, as expressed in the perldoc perldelta manpage, "File handles can be opened to "in memory" files held in Perl scalars via open($fh,'>',\$variable) || ...."
However, all is not lost. Read on to my second update to see how to do it in any version using the module Tie::STDERR.
That ought to do the trick. ...at least under 5.8.0+. It gets even more fun when you use it to redirect STDOUT to a scalar. It's too bad it didn't exist prior to 5.8.0.
Under pre-5.8.0 versions of Perl (or post-5.8.0 too if you wish, though it becomes unnecessary), you could use the module: Tie::STDERR
From that point on, STDERR will be routed to the scalar. The module can also be used to redirect STDERR to email, or to a function that is called upon program exit. If you look into the module's internals you see that 'tie' is being used to tie *STDERR to the package named Tie::STDERR, and then the module is holding onto anything that would have been writen to STDERR and appending it to the scalar you supply in the use Tie::STDERR .....; line.
I hope this helps for you too.
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein