in reply to Re: can the default file handle be localized?
in thread can the default file handle be localized?

And I was going to link an earlier node of yours: Re: Localized STDIO and system()

  • Comment on Re^2: can the default file handle be localized?

Replies are listed 'Best First'.
Re^3: can the default file handle be localized?
by ikegami (Patriarch) on Mar 12, 2009 at 21:57 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; ... }