jay469 has asked for the wisdom of the Perl Monks concerning the following question:

How do I redirect <STDOUT> (default output to screen) to a file in Perl?

Replies are listed 'Best First'.
Re: STDOUT redirect in Perl
by ehdonhon (Curate) on Nov 14, 2001 at 08:45 UTC
    The most simple way is to use select().
    open ( OUTFILE, '>myfilename.txt' ); print "This goes to the screen\n"; select ( OUTFILE ); print "This goes to the file\n";

    The other method that works is using typeglobs.

    open ( OUTFILE, '>myfilename.txt' ); print "This goes to the screen\n"; *STDOUT = *OUTFILE; print "This goes to the file\n";

    Personally, I prefer the select method.

      You don't need to mess with typeglobs to do the second.
      open(STDOUT, '> myfilename.txt'); #reopen STDOUT as a file print "This goes to the file\n";

      Or
      open(OUTFILE, '> myfilename.txt'); print "This goes to the screen\n"; open(STDOUT, '>&OUTFILE'); #dup STDOUT to OUTFILE print "This goes to the file\n";
Re: STDOUT redirect in Perl
by staeryatz (Monk) on Nov 14, 2001 at 14:08 UTC
    Even more Temporarily, you can specify the filehandle with print, instead of using select.
    open(OFILE, ">test.txt"); # make a filehandle print OFILE "this is a test.\n"; # print to filehandle
    Using this way is good if you only have to print one time, instead of using 'select'. It is really not a good idea to change STDOUT, but rather just make a new filehandle like 'OFILE' shown above.