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.
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.
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
In reply to Re: Best Way to Redirect STDERR to a Scalar
by davido
in thread Best Way to Redirect STDERR to a Scalar
by Mr. Muskrat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |