Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Redirecting STDOUT, lexically scoped

by moritz (Cardinal)
on Jul 31, 2007 at 09:33 UTC ( #629771=perlquestion: print w/replies, xml ) Need Help??

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

I read how do i redirect STDOUT, STDIN, or STDERR to a FILE?, and started to wonder if that can be done lexically scoped.

For some tasks it would be cool to redirect STDOUT to a file or to a scalar (with IO::Scalar), but only in certain scope.

Of course local STDOUT dies with Can't modify constant item in local....

Is there a clean solution?

Update: I just found IO::String and select which works for STDOUT, but is there a way for STDERR as well? I don't need it, I'm just curious ;-)

Replies are listed 'Best First'.
Re: Redirecting STDOUT, lexically scoped
by wind (Priest) on Jul 31, 2007 at 09:43 UTC
    print "Hello world\n"; { local(*STDOUT); open(STDOUT, ">some_other_world.txt") or die $!; print "Hi other world\n"; close STDOUT; } print "Goodbye world\n";
    - Miller

        Do you understand why? The leading * is there because you're localizing the typeglob. As a result, you'll also effectively localize any $STDOUT, @STDOUT, or %STDOUT you may have defined.

        Not likely to be a problem, but something that bit me at least once as a novice... ;-)

        Ramblings and references
        The Code that can be seen is not the true Code
        I haven't found a problem yet that can't be solved by a well-placed trebuchet
Re: Redirecting STDOUT, lexically scoped
by FunkyMonk (Chancellor) on Jul 31, 2007 at 09:45 UTC
    Use local *STDERR:

    my $out; print STDERR "before\n"; { local *STDERR; open STDERR, ">", \$out or die; print STDERR "during\n"; } print "after\n"; print "out: $out\n";


    before after out: during

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://629771]
Approved by almut
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2021-06-22 17:58 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (108 votes). Check out past polls.