If you have a very low traffic application, locking the file may seem like overkill. However, it only takes two people to happen to hit the web site at the same time to causesome very unhappy results. The first rule of thumb is that if you find that you are getting frequent data file corruptions that can be traceable to two simultaneous records in your server access log, it is probably time to move to a real database, where you will not have to deal with things like this.
OK, safety tip - don't actually try to get a lock on your data file, but get a lock on a separate lock file. The reason for this is that, in Perl, flock acts on a file handle, and you can only have a file handle if you have already opened the file. This means that if you open the file for writing, and then cannot get a lock of the file, you have already blown away the contents of the file. This is a Bad Thing, and can be avoided by using a completely different file for the lock file.
# Get a lock on the lock file
$lockfile = $filename . ".lock";
open (LOCK, ">$lockfile");
flock LOCK, 2;
# Write data to data file.
open (DATA,">>$filename")
or die ("Was unable to open $filename file for writing: $!\n");
for $data (@new_data) {
print DATA "$data\n"
} # End for
close DATA;
# Release lock
flock LOCK, 8;
close LOCK;