When using advisory locking, make sure that all your programs are playing along. If multiple scripts need to alter counter.dat, for example, make sure that they all follow the same scheme.
File locking may not work across file-sharing systems such as NFS. Some operating systems, such as Windows NT, may not allow advisory locking. Read the documentation for your system, as well as the documentation in Perl about file locking.
Although you can do the file locking yourself, as shown in this article, you can also use one of a few modules on the Comprehensive Perl Archive Network (CPAN):
Using a module from the CPAN to do your locking doesn't mean that the flow of your program should be any different. Remember to remove the locking from the resource, and you should be safe from these kinds of race conditions. Until next time, enjoy!