open my $FH, ">the_file"; # zero-byte the file
flock($FH, LOCK_EX); # and Then lock it...
####
open my $FH, "the_file"; # open for reading
flock($FH, LOCK_SH); # lock it
my @lines = <$FH>; # read it
open $FH, ">the_file"; # open for writing: LOCK DROPPED.
# Now someone else picks up the lock and finds an empty
# file. When they're finished,
flock($FH, LOCK_EX); # lock it again
push @lines, "new line\n"; # process the lines
print $FH for (@lines); # write them out
close $FH; # close and drop lock
####
# Open a different file as a semaphore lock
open my $SEM, ">the_file.semaphore";
flock($SEM, LOCK_EX); # lock it
# then process the Real File
open my $FH, "the_file";
my @lines = <$FH>; # read it
# because we never fiddle with $SEM, we still have a lock
open $FH, ">the_file"; # open for writing.
push @lines, "new line\n"; # process the lines
print $FH for (@lines); # write them out
close $FH; # close the file
close $SEM; # close and unlock semaphore
####
# Open the file for locking purposes only
open my $SEM, "the_file";
flock($SEM, LOCK_EX); # lock it
# Process it
open my $FH, "the_file";
my @lines = <$FH>;
open $FH, ">the_file";
push @lines, "new line\n";
print $FH for (@lines);
close $FH;
close $SEM; # close and unlock semaphore