2010-07-26 76 views
1

对于同一个文件,可能有两个文件句柄吗?perl中同一个文件的两个文件句柄

open TXT,"+>","New" or die "Cannot Create File \n"; 
print TXT "Line1 \n"; 
open TXT1, ">>New" or die "Cannot open file"; 
print TXT1 "Line2 \n"; 

这项工作?

+3

正如那句老话:“当你尝试它时发生了什么? – hobbs 2010-07-26 10:49:05

+0

是的..它工作。感谢所有.. – Raj 2010-07-28 12:55:42

回答

1

,对同一文件可能有多个文件处理程序。 这将工作。

use strict; 
    use warning; 
    my $path = 'testfile'; 
    open TXT,"+>",$path or die "Cannot Create File \n"; 
    printf TXT "Line1\n"; 

    open TXT1, ">>",$path or die "Cannot open file"; 
    printf TXT1 "Line2\n" ; 
    close TXT; 
    close TXT1; 
3

是的,它会工作。对同一个文件有几个句柄是可以的。

但请注意,您的第一个文件处于覆盖模式。 TXT1将始终在文件末尾写入,但TXT将保留在其以前的位置并根据缓冲区重写所有内容。

如果你这样做:

print TXT "Line 1\n"; 
print TXT1 "Line 2\n"; 
print TXT "Line 3\n"; 
close TXT; 
close TXT1; 

您将有:

Line 1 
Line 3 
Line 2 

,但如果你这样做:

print TXT "Line 1\n"; 
print TXT1 "Line 2\n"; 
close TXT1; # this writes the buffer to disk 
print TXT "Line 3\n"; 
close TXT; 

您将有:

Line 1 
Line 3 

第2行被写入,然后被第3行覆盖。在第一种情况下,第3行位于缓冲区中,第2行被写入,因为文件首先关闭,然后第3行写入追加。

所以,小心使用!

1

是的,可以为同一个文件打开多个句柄,但(1)结果可能不是你想要的(见下文),(2)你是否真的需要这样做,或者有更好的如何解决你的大问题?

这就是说,这里就是一个小实验发现我的Windows机器上:在写模式

打开一个文件,追加模式一个文件:

my $file_name = 'text_write_append.txt'; 
open(my $fh1, ">", $file_name) or die $!; 
open(my $fh2, ">>", $file_name) or die $!; 

print $fh1 "foo\n" x 1; 
print $fh2 "bar\n" x 2; 
print $fh1 "x"; 

第二写$fh1选秀权在先前的写入停止的地方,跺倒第一个bar并截断第二个。可能不是你想要的。

foo 
xar 

打开追加模式这两个文件。

my $file_name = 'text_append_append.txt'; 
open(my $fh0, ">", $file_name) or die $!; close $fh0; # Create empty file. 
open(my $fh1, ">>", $file_name) or die $!; 
open(my $fh2, ">>", $file_name) or die $!; 

print $fh1 "foo\n" x 1; 
print $fh2 "bar\n" x 2; 
print $fh1 "x"; 

我们所有的输出都存在,但顺序错误。

bar 
bar 
foo 
x 

开启在附加模式这两个文件,无需缓冲输出

my $file_name = 'text_append_append_flush.txt'; 
open(my $fh0, ">", $file_name) or die $!; close $fh0; 
open(my $fh1, ">>", $file_name) or die $!; select $fh1; $| = 1; # No buffering. 
open(my $fh2, ">>", $file_name) or die $!; select $fh2; $| = 1; 

print $fh1 "foo\n" x 1; 
print $fh2 "bar\n" x 2; 
print $fh1 "x"; 

可能是您期望的(但请注意,无缓冲写入通常比缓冲写入更慢)。

foo 
bar 
bar 
x 
相关问题