Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

stdout back to the normal ??

by iza (Monk)
on Nov 13, 2001 at 22:21 UTC ( [id://125103]=perlquestion: print w/replies, xml ) Need Help??

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

hi :)

my code is
open STDOUT, ">$file" || die "Cannot open file $file : $!"; system "diff $old_file $file"; select(STDOUT); # Restore default print to STDOUT close(STDOUT);
but the default print is never ever restored to stdout (i mean, as long as the program runs !)
i don't know how to restore defaut print ... can anyone help ??

Replies are listed 'Best First'.
(jeffa) Re: stdout back to the normal ??
by jeffa (Bishop) on Nov 13, 2001 at 22:55 UTC
    Hi, this is straight from Dr. Stein's excellent Network Programming in Perl book:
    print "redirecting STDOUT\n"; open (SAVEOUT, ">&STDOUT"); open (STDOUT, ">$file") or die "Can't open $file: $!"; #STDOUT is now redirected system "diff $old_file $file"; open (STDOUT, ">&SAVEOUT"); print "STDOUT is back to normal!\n";

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
Re: stdout back to the normal ??
by davis (Vicar) on Nov 13, 2001 at 22:58 UTC
    Hi, I think the problem is the open STDOUT. You're redirecting the output of STDOUT to $file, and in fact the select(STDOUT) doesn't acheive anything, because the default output handle is already STDOUT.
    Another way around would be to open a read pipe from a system command, like this:
    #!/usr/bin/perl -w use strict; my $output = "out.txt"; open(OUT, ">$output") or die "Couldn't open $output: $!\n"; open(IN, "date|") or die "Couldn't open date|: $!\n"; print OUT <IN>; close(OUT); close(IN); print "This gets printed to stdout.\n";
    There are, of course, other ways to do it, but that's something for some more experienced monks to attempt :).
Re: stdout back to the normal ??
by chromatic (Archbishop) on Nov 16, 2001 at 00:28 UTC
    Is this better?
    { local *NEWOUT; open(NEWOUT, "> $file") or die "Cannot open ($file): $!"; my $oldfh = select(NEWOUT); # print some stuff here select($oldfh); }
    Of course, if you're going to run a system call, you might just use shell redirection to the file. There's more than one way to tame this camel. (Caveat added because I'm not sure redirecting STDOUT in a Perl parent will affect the non-Perl child.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-19 05:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found