$ptr = &lock_file($path); # load $path with a regular open and do whatever operations on data... &unlock_file($ptr); sub lock_file { # Locks file by creating filepath.lock and flocking it. # Usage: $ptr = &lock_file($path); my $handle; my $path = (shift) . '.lock'; open($handle, ">$path"); flock($handle, 2); return [$handle, $path]; } sub unlock_file { # Unlocks file locked with &lock_file. # Usage: &unlock_file($ptr); my $inp = shift; my ($handle, $path) = @$inp; flock($handle, 8); close($handle); unlink($path); }