Home » Perl » stderr, local block and redirection

stderr, local block and redirection

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 or die $!;
     print $output if $output;
  }
}

test_stderr;
test_stderr;

The solution apparently is to initialize the $output variable with an empty (non undef) value:

#!/usr/bin/perl

use strict;
use warnings;

sub test_stderr {
 {
   my $output = "";

   open local(*STDERR), ‘>’, $output or die $!;
   print $output if $output;
 }
}

test_stderr;
test_stderr;

At this time, I’m not sure as to why this is necessary, but I’ve asked on Perlmonks.org as to an explanation.

UPDATE:

Fletch from Perlmonks.org explained why:

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.

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*

Facebook login by WP-FB-AutoConnect