in reply to Best Way to Redirect STDERR to a Scalar
UPDATE:
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.
my $variable; # First, save away STDERR open SAVEERR, ">&STDERR"; close STDERR; open STDERR, ">", \$variable or die "What the hell?\n"; # Now print something to STDERR, redirected to $variable print STDERR "This is a test.\n"; # Now close and restore STDERR to original condition. close STDERR; open STDERR, ">&SAVEERR"; # Now test to see if $variable actually received the text. print "Now for the real test.\n"; print $variable;
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.
UPDATE:
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
use Tie::STDERR \$append_to_scalar;
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.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Best Way to Redirect STDERR to a Scalar
by shenme (Priest) on Sep 13, 2003 at 23:57 UTC | |
by davido (Cardinal) on Sep 14, 2003 at 01:06 UTC |