#!/usr/bin/perl use strict; use warnings; use Fcntl qw(:flock); $| = 1; # Flush the output my $file = "perl.txt"; open( FH , "+<" , $file ) or die "Unable to open '".$file."' - $!\n"; flock( FH , LOCK_EX ) or die "Could not lock '".$file."' - $!\n"; =notes +< open a file for updating without truncating it. (truncating means empties the file before opening it. flock exclusive lock or FH , 2 but better LOCK_EX because, might not be the right number on all operating systems. =cut seek( FH , 0 , SEEK_END ) or die "Cannot seek - $!\n"; # put the pointer at the end of file for writing. truncate( FH , 0 ) or die "Cannot truncate - $!\n"; print FH "This is line-1."\n"; print FH "This is line-2."\n"; close(FH) or die "Could not write '".$file."' - $!\n";