Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

how do i redirect STDOUT, STDIN, or STDERR to a FILE?

by Buckaroo Buddha (Scribe)
on May 10, 2000 at 20:51 UTC ( #11007=perlquestion: print w/replies, xml ) Need Help??

Buckaroo Buddha has asked for the wisdom of the Perl Monks concerning the following question: (input and output)

I wanted to do something like the following.
open( FILE, $file ); redirect( STDOUT, FILE );
Your mission: define sub redirect. :-)

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: how do i redirect STDOUT, STDIN, or STDERR to a FILE?
by perlmonkey (Hermit) on May 11, 2000 at 07:02 UTC
    The easist way to do this is to use fdopen from IO::Handle:
    use IO::Handle; open INPUT, '<', "input.txt" or die $!; open OUTPUT, '>', "output.txt" or die $!; open ERROR, '>', "error.txt" or die $!; STDIN->fdopen( \*INPUT, 'r' ) or die $!; STDOUT->fdopen( \*OUTPUT, 'w' ) or die $!; STDERR->fdopen( \*ERROR, 'w' ) or die $!; # prints to output.txt: print "Hello Output File\n"; # reads everything from input.txt and prints it to output.txt: print <>; # prints to error.txt: warn "Hello Error File\n";
Re: how do i redirect STDOUT, STDIN, or STDERR to a FILE?
by plaid (Chaplain) on May 10, 2000 at 21:17 UTC
    The typical way to do this would be in the way you run it from the command line, e.g.
    ./script.pl < infile > outfile
    This would take STDIN from infile and put STDOUT to outfile. The sh type shells and csh type shells have different ways to do STDERROR. Under bash, you'd do something like
    ./script.pl < infile > outfile 2> errfile
Re: how do i redirect STDOUT, STDIN, or STDERR to a FILE?
by pwesthagen (Initiate) on Apr 04, 2012 at 22:52 UTC
    Try this, worked for me:
    open FILE, ">$file"; select FILE; # print will use FILE instead of STDOUT print "Hello, world!"; # goes to FILE select STDOUT; # back to normal print "Goodbye."; # goes to STDOUT

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11007]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2021-04-18 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?