A series of comments:
- I would not assume that the data file
had a name ending in .dat. That is the kind of assumption
that can change, and then people will be unhappy because
their data file got wiped out.
- You need to set the LOCK_NB flag as well as LOCK_EX
or else your first try will hang until you get the lock.
- In a CGI environment, waiting 1 second per retry is
probably a bit much...
- While you have control of the file, you don't need to
be cautious about truncates and seeks. Just open for read,
read, close, open for write, and write as usual.
- Explicitly closing the data file is a good idea.
- However I like calling local on *FH if I will use
FH as a filehandle. Just a good practice...
UPDATE
Others have already said everything that I would have to
say other than the fact that my fifth point is that you
actually did. I offered you code earlier where the lock
went away just by going out of scope. If you use that
then you still want to be explicit about closing the date
file. I was just saying that it was subtle but important
point.