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

I'm running into an annoyance that I find rather purplexing. Maybe it is the fact that the closer I get to my wedding, the more my brain is shutting down that I can't seem to see the problem. :-p

I open the STDERR descriptor in a local block and redirect it to a variable. The first time I call it, it works fine. The second time, I get an uninitiallized value error

Use of uninitialized value in open at ./test_stderr line 10.

#!/usr/bin/perl use strict; use warnings; sub test_stderr { my $output; { open local(*STDERR), '>', \$output; } print $output if $output; } test_stderr; test_stderr;

open local(*STDERR), '>', \$output; <--- line 10

The STDERR descriptor is getting closed but wouldn't wrapping it in local() only affect the STDERR within the block? This is obviously a scope question...

Any clues for the clueless me?

Jason L. Froebe

Team Sybase member

No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1

Replies are listed 'Best First'.
Re: stderr, local block and redirection
by Fletch (Bishop) on Sep 13, 2006 at 16:54 UTC

    Try my $output = ""; instead. And you may actually want to print something to STDERR inside the block.

    #!/usr/bin/perl use strict; use warnings; sub test_stderr { my $output = ""; { open local(*STDERR), '>', \$output; print STDERR "CATCH ME IF YOU CAN\n"; } print "\$output is '$output'\n" if $output; } test_stderr; print STDERR "I'm not caught\n";

    Update: Gah, got a halfway version in my clipboard. Tweaked slightly.

      Woohoo! that worked! :) Why would setting $output to a non undef value make it work?

      Jason L. Froebe

      Team Sybase member

      No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1

        Although it's not explicitly explained that I can find, my guess would be that under the hood it needs an actual not-undef SvPV* into which the data is written. Otherwise it's going to be trying to append things to the single global undefined value &PV_sv_undef which is what throws the error.

Re: stderr, local block and redirection
by davido (Cardinal) on Sep 13, 2006 at 16:56 UTC

    What happens when you check the return value of open by adding the following to line 10?

    or die $!;

    Dave

      Same error message. :( Looks like I wrongly assumed that the STDERR was being closed. My drill sgt from back in 1990 told me never to assume anything. I knew I should have listened ;-)

      Jason L. Froebe

      Team Sybase member

      No one has seen what you have seen, and until that happens, we're all going to think that you're nuts. - Jack O'Neil, Stargate SG-1