I am writing the file using Perl. There is a situation where after writing 4 lines, I have to go back 4 lines and write something then come back to end of file and again start write. Is there any way to move file handle position line wise?
How can I change File pointer position 4 line back while writing the file using perl?
779 views Asked by Sanket At
2
There are 2 answers
5
On
You can use Tie::File to do all the magic for you. It ties a file to an array so each line is represented by an array element. Tying is a mechanism that is very powerful, but seems to be considered very advanced1 nowadays.
That makes it possible to use normal array operations like push
and unshift
or even splice
on the file. You don't need to put newlines. It uses $/
automatically.
use Tie::File;
tie my @file, 'Tie::File', 'foo.txt' or die $!;
push @file, "Line 1";
push @file, "Line 2";
push @file, "Line 3";
push @file, "Line 4";
push @file, "Line 5";
# to overwrite
$file[-4] = 'Line 6 overwrote line 2';
# to append
$file[-3] .= ' and Line 7';
# to insert
splice @file, -2, 0, 'Line 8';
The file will now contain:
Line 1
Line 6 overwrote line 2
Line 3 and Line 7
Line 8
Line 4
Line 5
1) I say advanced, but really I mean that it is not widely spread or understood nowadays. There are not a lot of learning materials that cover tie
, and the original use-case of database file access is quite dated and. I would say a lot of people have never heard of it, though it's a powerful feature.
You can indeed move the position around using
seek
. Files don't have indexes of lines, though, so you'll either have to keep track of the position of lines (as obtained usingtell
) as you write them, or discover them using an approach similar to File::ReadBackwards's.What do you want to happen to the contents of the file that's between the position to which you seek and the end of the file? You will need to copy it if you want to insert lines, or
truncate
the file if you want to delete it.If you can, maintain a buffer instead.