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; ... }
In reply to Re^3: can the default file handle be localized?
by ikegami
in thread can the default file handle be localized?
by perl5ever
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |