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

I have been writing perl code for 2 months now. And I need to redirect STDOUT to a file and then close the file and redirect STDOUT back to the screen for the rest of the script. I know how to redirect to a file I just can not get the STDOUT back to the screen afterward. Any help would be apperciated.

Replies are listed 'Best First'.
Re: Redirecting STDOUT
by Tomte (Priest) on Jun 18, 2003 at 19:53 UTC

    Straight out of perldoc -f open:

    # Here is a script that saves, redirects, and restores "S +TDOUT" # and "STDERR" using various methods: #!/usr/bin/perl open my $oldout, ">&STDOUT" or die "Can't dup S +TDOUT: $!"; open OLDERR, ">&", \*STDERR or die "Can't dup S +TDERR: $!"; open STDOUT, '>', "foo.out" or die "Can't redirect +STDOUT: $!"; open STDERR, ">&STDOUT" or die "Can't dup STDOU +T: $!"; select STDERR; $| = 1; # make unbuffered select STDOUT; $| = 1; # make unbuffered print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too close STDOUT; close STDERR; open STDOUT, ">&", $oldout or die "Can't dup \$oldo +ut: $!"; open STDERR, ">&OLDERR" or die "Can't dup OLDERR +: $!"; print STDOUT "stdout 2\n"; print STDERR "stderr 2\n";

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

Re: Redirecting STDOUT
by Nkuvu (Priest) on Jun 18, 2003 at 19:54 UTC
Re: Redirecting STDOUT
by nimdokk (Vicar) on Jun 18, 2003 at 19:51 UTC
    One way to do this is:

    open(STDOUT, ">>log.file"); #open STDOUT and direct into log.file print "test\n"; #print to STDOUT directed into log.file close STDOUT; #close the redirection to STDOUT open (LOG, "log.file"); #open log.file under a new FileHandle foreach (<LOG>) { print; } #loop through and print each line.
    Very simple example, but that should do what you are looking for. There are a few other things that probably should be done, such as saving STDOUT before redirecting into it then restoring STDOUT when you are done. Hope that helps some, you might take a look at the open() descriptions in the Camel Book.


    "Ex libris un peut de tout"
Re: Redirecting STDOUT
by waswas-fng (Curate) on Jun 18, 2003 at 20:10 UTC
    Just taking a step back for a second, you are not redirecting STDOUT to a file to then later in your script parse that file are you? =)

    -Waswas