in reply to can the default file handle be localized?

use Sub::ScopeFinalizer qw( scope_finalizer ); { my $old_fh = select($fh); my $sentry = scope_finalizer { select($old_fh); }; ... }

Sub::ScopeFinalizer

Replies are listed 'Best First'.
Re^2: can the default file handle be localized?
by hbm (Hermit) on Mar 12, 2009 at 21:44 UTC

      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; ... }