The OP wants the file handle to be restored automatically on scope exit. The linked node does not provide a means of doing so.
In fact, Scope::Finalizer could have been used in that post too.
use Sub::ScopeFinalizer qw( scope_finalizer );
{
open(my $old_stdout, '>&', *STDOUT) or die;
my $sentry = scope_finalizer {
close(STDOUT);
open(STDOUT, '>&', $old_stdout) or die;
};
close(STDOUT);
open(STDOUT, '>', $file) or die;
...
}
The only reason I didn't is that "..." is a call to system, and that doesn't die or otherwise exit the block.
Update: I missed it since the point of the linked post was to avoid using local *STDOUT in the circumstances of that thread, but local *STDOUT is a simpler alternative to using select + scope_finalizer:
{
local *STDOUT = $OLDFH;
...
}
|