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

I am using select to change the default output filehandle to STDERR. I want the default output filehandle to be STDERR even for any subroutines I call. Is there anyway to do this? Basically I want to say at the top of my script:
unless(-t STDERR) { select STDERR; }
and I want this to take effect for the entire script including subroutines.

Replies are listed 'Best First'.
Re: use 'select' to change default output handle for entire script
by ikegami (Patriarch) on Nov 19, 2004 at 16:02 UTC

    Is there any reason to believe select doesn't do all of that?

    $ cat > script.pl print('!', $/); select(STDERR); sub test { print('@', $/); } test(); ^D $ perl script.pl 2>stderr ! $ cat stderr @ $

    Are you worried that someone will select something else?

      No, i had reason to believe select doesn't do that but it was my fault...I was launching the scripts from a Win32 app and CreateProcess() wasn't using the one in my PATH beucase of the search order blah blah.

      Bottom line, you're right and select does all of what I wanted.

Re: use 'select' to change default output handle for entire script
by nimdokk (Vicar) on Nov 19, 2004 at 14:32 UTC
    I suppose you could do something like:

    open STDOUT, ">>&STDERR" or die "Cannot redirect STDOUT to STDERR. $!" +;
      Hmm, but then if I really wanted to use STDOUT I'd have to reopen it right?
        Then first open a filehandle to your old STDOUT, before redirecting STDOUT:
        open OLDSTDOUT ">&STDOUT" or die "oops: $!"; open STDOUT ">&STDERR" or die "oops: $!"; print OLDSTDOUT "Still to STDOUT..\n";
        Paul