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

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

Dear Wise Monks, One of my programs has a simple counter that counts the number of times the program has run. Below is the relevent portion that handles this task. My problem is that sometimes the counter mysteriously loses count and starts from the beginning again, as if the contents were erased somehow. This happens during times when traffic is high and people are accessing the script at the same time on the internet. Can you shed light on why the file contents "disappear"? Thanks in advance.
$completeadd = "mycounter"; $semaphore_file = "mycounterlock"; open(SEM, ">$semaphore_file") || die "Cannot create semaphore $semapho +re_file: $!"; flock(SEM, LOCK_EX) || die "Lock failed: $!"; open(MFILE, ">>$completeadd") || die "file open1 failed: $!\n"; close(MFILE); open(MFILE, "$completeadd") || die "file open2 failed: $!\n"; @filedata1=<MFILE>; chomp @filedata1; close(MFILE); $hitcount=$filedata1[0]; if ($hitcount) { $hitcount=$hitcount + 1; } else { $hitcount = 1; } $filedata1[0]=$hitcount; writedata(@filedata1); release_lock();