Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to redirect STDOUT

Status
Not open for further replies.

redsss

Programmer
Mar 17, 2004
72
US
I want my perl program to print to STDOUT on the console, then redirect so that STDOUT goes into a file, then redirect again so that STDOUT goes to the console. I figured out how to redirect to a file, but I can't figure out how to redirect BACK to the console. HELP!

PS: the reason I have to use STDOUT rather than a different file handle is because I want to execute a system() command that will generate output that goes to STDOUT.

Code:
print "printing to screen\n";

open(STDOUT, ">file.txt");    # redirects to file
print "redirected to file\n";

# How do I redirect back to screen?

print "back to screen\n";
 
copy STDOUT before redirect:

Code:
#first, dup STDOUT 

open (OLDSTDOUT, "&>STDOUT) or die "Couldn't dup STDOUT: $!"; 

#re-direct STDOUT to log 

open (STDOUT, ">> $logfile") or die "Can't open $logfile: $!"; 

system "$executable"; 

close STDOUT; 

#restore original STDOUT 

open (STDOUT, "&>OLDSTDOUT) or die "Can't restore STDOUT: $!"; 

close OLDSTDOUT;
 
You could use backticks to execute your shell command

Code:
@output=`ls -lsa`;
foreach (@output) {
  print "$_\n";
}

HTH
--Paul
 
btaber has the right idea but the syntax is a bit off:

Code:
open (OLDSTDOUT, "[b][red]&>[/red][/b]STDOUT) or die "Couldn't dup STDOUT: $!";
.
.
.
open (STDOUT, "[b][red]&>[/red][/b]OLDSTDOUT) or die "Can't restore STDOUT: $!";

Should read:

Code:
open (OLDSTDOUT, "[b][blue]>&[/blue][/b]STDOUT) or die "Couldn't dup STDOUT: $!";
.
.
.
open (STDOUT, "[b][blue]>&[/blue][/b]OLDSTDOUT) or die "Can't restore STDOUT: $!";
 
How about:
Code:
open FILE, ">file" or die;
print "to stdout\n";
$fh = select(FILE);
print "to file\n";
select($fh);
print "to stdout again\n";
Cheers, Neil
 
For my purposes, paulTEG's suggestion will work great. I hadn't thought of using backticks. Thanks everyone!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top