Reputation: 637
I have redirected STDOUT
in a Perl script. Everything I print in my module is redirected to a file. Is there a way to restore STDOUT
in a Perl module?
Here is my example
require my_module;
open(STDOUT, ">$outlog") || die "Error stdout: $!";
open(STDERR, ">>$outlog") || die "Error stderr: $!";
my_module::my_func();
So I want to print a message on STDOUT
in my_module::my_func()
function and exit.
Upvotes: 4
Views: 3519
Reputation: 637
Seems I found solution. First I saved STDOUT
in main script then I used it in module.
require my_module;
open(SAVEOUT, ">&STDOUT") || die "Unable to save STDOUT: $!";
open(STDOUT, ">$outlog") || die "Error stdout: $!";
open(STDERR, ">>$outlog") || die "Error stderr: $!";
my_module::my_func();
In my_module::my_func()
I added the following line before exiting
open (STDOUT, ">&main::SAVEOUT") or die "Unable to restore STDOUT : $!";
print "a_module!!!\n";
My printed message was sent to STDOUT
Upvotes: 2
Reputation: 181
Actually you can't restore STDOUT unless you save it at some other location.
You can do following:
# Save current STDOUT handle in OLDOUT
open (OLDOUT, ">&STDOUT") or die "Can't open OLDOUT: $!";
# Set STDOUT to a your output file
open (STDOUT, ">$youroutputfile") or die "Can't open STDOUT: $!";
# Do whatever you want to do here.......
# ...........
# Close STDOUT output stream
close (STDOUT);
# Reset STDOUT stream to previous state
open (STDOUT, ">&OLDOUT") or die "Can't open STDOUT: $!";
# Close OLDOUT handle
close (OLDOUT);
# Here your preview STDOUT is restored....
:)
Upvotes: 2