http://www.perlmonks.org?node_id=659032

CColin has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a program which modifies a file in place using a temporary file
open(OLD, "< $old") or die "can't open $old: $!"; open(NEW, "> $new") or die "can't open $new: $!"; my @array = <OLD>; my $required_element_details = shift(@array); foreach my $remaining_details (@array) { print NEW "$remaining_details"; } close(OLD) close(NEW) rename($new, $old)
Problem is this file can be accessed at the same time by the same program so the reading and writing process needs to be locked. Have tried:
open(OLD, "< $old") or die "can't open $old: $!"; open(NEW, "> $new") or die "can't open $new: $!"; flock (OLD, 2); flock (NEW, 2); [continue as before including renaming the file before the filehandles + are closed]
But this doesn't work when both programs are trying at the same time, instead both programs read the same initial element (and write the same results). Any suggestions? Colin