I couldn't really decide where to put this, but I figured Meditations would be best.
I was working with a script yesterday and realized that flock() doesn't do much by itself.
Using a simple flock FILEHANDLE, LOCK_EX; won't always succeed in locking a file.
So, I created a subroutine that attempts to lock a file several times, and if it cannot, there is definitely something wrong, and the user is presented with an error.

So here is the small subroutine:

sub lockfile { my $file = pop(); for $i (1 .. 10) { sleep .15; $locked = 1 if (flock $file, LOCK_EX); } unless ($locked == 1) { print "\n\nFlock error: could not lock $file"; + exit; } }
There. Very easy subroutine that will try flocking a file 10 times before informing the user of an error.
I surprised myself by using pop()!
Anyway, this code is very easy to use:
lockfile (FILEHANDLE);

I could have also allowed an optional parameter that would allow the user to pass what kind of lock to use, rather than simply applying LOCK_EX, but I always use LOCK_EX, so...

Better not be an error in that post... ;-)