cat -E test1.txt

输出:
car$
$
$

我只想用“bike”更改“car”并删除新行/空行。

这按预期方式工作:
#!/usr/bin/perl -w
open(FILE1,"<","./test1.txt"); @araj=<FILE1>; close(FILE1);
open(FILE2,">","./test1.txt");
map {
s@car@bike@; s@^\n@@;
} @araj;
print(FILE2 @araj);
close(FILE2);


cat -E test1.txt

输出对我来说是100%正确的:
bike$

但在上述情况下,我正在使用2x打开/关闭文件。
所以我正在使用2x文件句柄。
我只想使用 1x 文件句柄
(出于学习目的,只是试图了解+> + >> >>的工作方式...)。
例如:
#!/usr/bin/perl -w
open(FILE2,"+<","./test1.txt"); #what file handle should be here? +> , +>> >> .... ?
@araj=<FILE2>;
map {
s@car@bike@; s@^\n@@;
} @araj;
print(FILE2 @araj);
close(FILE2);

输出不正确:
car$
$
$
bike$

为什么要附加,但不覆盖?当我使用其他文件句柄时,结果也不正确,例如空文件...
哪个文件句柄用于读写?

最佳答案



您已首先读取所有数据,直到文件末尾。这意味着下一次读取或写入的文件位置现在位于您已读取的所有数据之后,即位于文件末尾。如果要从文件开头写入数据,则需要使用seek更改文件位置:

 seek($filehandle,0,0); # position at beginning of file

然后,您写入的下一个数据将从该新文件位置开始写入,即从文件开头开始写入。一旦完成,您可能需要通过使用truncatetell获得的当前文件位置,从文件中删除当前文件位置之后的所有数据:
 truncate($filehandle, tell($filehandle));

或者,整个程序:
use strict;
use warnings;
open(my $fh, "+<", "./test1.txt");
my @araj = <$fh>;
for(@araj) {
    s{car}{bike};
    s{^\n}{};
}
seek($fh, 0, 0);           # seek at the beginning of the file
print $fh @araj;
truncate($fh, tell($fh));  # remove everything after current file position
close($fh);

10-07 12:43
查看更多