#!/usr/local/bin/perl use Fcntl qw(LOCK_EX LOCK_UN LOCK_NB); # This opens a file in a lexcially scoped file handle, and flocks it. # It will close and unlock when that variable goes out of scope. sub fn { my $fn = "FOO"; open my $F, ">$fn"; flock($F, LOCK_EX) or die "no lock"; return $fn; } # In this case, for some reason $F above isn't destroyed until after # the for loop completes. for my $fn (fn()) { open my $G, $fn; flock($G, LOCK_EX|LOCK_NB) or warn "no lock 2"; }