First, the XY Problem: I have some existing code whose output I want to capture, modify, and then write to a file. To do this, I'm reopening STDOUT to write to a scalar.
The problem is, the second time I do this, I get a warning ("Use of uninitialized value in open"). The first time, there's no problem. I'd like to know where the warning is coming from and how to avoid it.
What follows is a short program to demonstrate the problem. In production code, there's "or die" after every open and close. I've taken them out for this example to make it easier to read. Those calls do not fail when I run it.
use strict; use warnings; require v5.8; my $hello1 = dupe_and_back(); my $hello2 = dupe_and_back(); print $hello1, $hello2; sub dupe_and_back { print "call to dupe_and_back\n"; my $output; open my $old_stdout, '>&=', \*STDOUT; close STDOUT; # Use of uninitialized value in open at the following line open STDOUT, '>', \$output; print "Hello world\n"; open STDOUT, '>&=', $old_stdout; return $output; } __END__ call to dupe_and_back call to dupe_and_back Use of uninitialized value in open at perlmonks.pl line 21. Hello world Hello world
Thanks in advance.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |