in reply to Avoiding a race condition

There's no need to unlock the file before closing. On older versions of Perl, this can result in data loss because unlocking can happen while there are unflushed buffers. Newer Perls do a flush before unlocking.

Just truncate the file to zero and close.

For finer-grained control, look at a combination of sysopen with the O_EXCL flag and flock. See perldoc perlopentut (which doesn't seem to be in the Library).