Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Redirecting STDOUT, lexically scoped

by moritz (Cardinal)
on Jul 31, 2007 at 09:33 UTC ( [id://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... ;-)

        <radiant.matrix>
        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";

    Output:

    before after out: during

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-20 05:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found