in reply to
Flock Updating Counter
There are also a number of locking modules that might help you (if this snippet is part of a larger script and not something quick and dirty):
LockFile::Simple especially can be quite handy -- it's very lightweight, however, and on the whole a database is a better way to handle this type of thing (unless the overhead is unecessary).
But the general answer is that you want to hold on to the lock until you're done writing out the new id and not grab one, release it after a read, then grab it again. Also, if you're using flock() it seems like you want an exclusive lock since you don't want another process to read the id value until it has been updated.