Perl write and read on same file

Hi,

I am trying to do a write operation followed by a read operation on the same file through Perl, expecting the output produced by read to contain the new lines added, as follows:

#! /usr/bin/perl -w

open FH, "+< testfile" or die "$@";
print FH  "New content added\n";
while (my $line = <FH>) {
    print "$line";
}
close(FH);

but the above code is sometimes corrupting the file's data (like replacing, globbering spaces etc.,). I have tried to flush the buffer but to no avail:

open FH, "+>> testfile" or die "$@";
$| = 1;
print FH  "New content added\n";
while (my $line = <FH>) {
    print "$line";
}
FH->autoflush(1);
close(FH);

I have even changed the mode to '+>', '+>>', but nothing works (i.e) the output is not printed with the lines recently added unless I close the file handle and reopen the file for reading.

Kindly help me how to modify the above Perl code to see the contents that are added by the previous write operation without closing the handle. Thank you.

The best option for such requirement is Tie::File

In anyway, you need to seek to the beginning of the file before reading it again.

#! /usr/bin/perl -w

open FH, "+< testfile" or die "$@";
print FH  "New content added\n";
# Move Curser to start
seek(FH,0,0);
while (my $line = <FH>) {
    print "$line";
}
# Move it to END
seek(FH,0,2);
close(FH);
1 Like