【发布时间】:2016-10-26 17:53:28
【问题描述】:
我有一个巨大的文本文件,前五行如下所示:
This is fist line
This is second line
This is third line
This is fourth line
This is fifth line
现在,我想在该文件第三行的随机位置写一些东西,它将用我正在编写的新字符串替换该行中的字符。我可以通过以下代码实现:
use strict;
use warnings;
my @pos = (0);
open my $fh, "+<", "text.txt";
while(<$fh) {
push @pos, tell($fh);
}
seek $fh , $pos[2]+1, 0;
print $fh "HELLO";
close($fh);
但是,我无法用同样的方法弄清楚如何从该文件中删除整个第三行,以便文本如下所示:
This is fist line
This is second line
This is fourth line
This is fifth line
我不想将整个文件读入数组,也不想使用 Tie::File。是否可以使用 seek 和 tell 来满足我的要求?解决方案将非常有帮助。
【问题讨论】:
-
为什么不想使用
Tie::File?我认为这将是实现此目的的理想选择。 -
@Borodin 即使是 Tie::File 也会将文件读入一个数组,这不会消耗内存吗?在这种情况下,模块的 -memory 选项可以提供一些帮助吗?