Create a lexical filehandle to be a copy of STDOUT
and manipulate that as needed
sub manip_fh {
my ($fh) = @_;
say $fh "hi"; # goes to STDOUT
open my $fh, '>', 'a_file.txt' or die $!; # now it's to a file
say $fh "hello";
}
open my $fh, '>&', STDOUT; # via dup2
manip_fh($fh);
say "hi"; # still goes where STDOUT went before being dup-ed (terminal)
This new, independent, filehandle can then be reopened to another resource without affecting STDOUT
. See open.
The $OUT_FILE_HANDLE = *STDOUT;
from the question creates an alias and so the STDOUT
does indeed get changed when the "new" one changes. You can see that by printing the typeglob
our $NEW = *STDOUT;
say *{$main::NEW}; #--> *main::STDOUT
or by printing the IO
slot from the symbol table for both
say for *{$main::NEW}{IO}, *{$main::{STDOUT}}{IO};
and seeing (that the object stringifies to) the same (eg IO::File=IO(0x1a8ca50)
).
When it's duped using open
with mode >&
as in the first code snippet (but as global our
) it prints *main::NEW
, and its IO::File
object is not the same as for STDOUT
. (Make it a global our
so that it is in the symbol table for this check, but not for real use; it's much better having a lexical.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…