如何关闭select in file write?

时间:2016-03-14 09:17:42

标签: perl

我使用select在文件中写入输出。

open my $handler, ">","newfile.txt";
select ($handler);
print "Something print into the file";
print "Something print into the file";
print "Something print into the file";

close $handler;  #This is not working

print "print into the terminal";

为此,我将在没有select

的情况下使用
open my $handler, ">","newfile.txt";
print $handler " print on file";
print "print on terminal";

使用select我该怎么办? 如何关闭select?我也想在终端上打印输出。

1 个答案:

答案 0 :(得分:2)

首先需要将默认文件句柄设置回原来的

my $old_fh = select($handle);    
# your prints ...
select $old_fh;
close $handle;

如果提供了表达式,select将设置新的默认文件句柄,并返回当前表达式。所以你拥有它的方式是你试图关闭默认的文件句柄。

来自perldoc -f select

  

选择FILEHANDLE   
  选择   
  返回当前选定的文件句柄。如果FILEHANDLE是   提供,设置新的当前默认文件句柄输出。这个   有两个效果:第一,“写”或“打印”没有   filehandle默认为此FILEHANDLE。第二,参考   与输出相关的变量将引用此输出通道。