sub openFileForAppending(*$)
{
my $handle = qualify_to_ref(shift, caller);;
my $name = shift;
open($handle, '>> ' . $name) or return;
attemptFlock($handle, LOCK_EX);
return $handle;
}
...
sub openFileForWriting(*$)
{
my $handle = qualify_to_ref(shift, caller);
my $name = shift;
# If a file with that name exists, we'll open it for reading and
# writing to prevent clobbering it prematurely before flock()ing it.
# If we can successfully open it, then we'll try to flock() it, *then*
# we can safely clobber it:
if (-e $name)
{
open($handle, '+< ' . $name) or return;
attemptFlock($handle, LOCK_EX);
seek($handle, 0, 0);
truncate($handle, 0);
}
else
{
open($handle, '> ' . $name) or return;
attemptFlock($handle, LOCK_EX);
}
return $handle;
}
####
openFileForWriting(TEST, 'test.txt');
print TEST "A test.\n";
close TEST;
####
openFileForWriting(TEST, 'test.txt');
print TEST test();
close TEST;
sub test
{
return "Another test.\n"
}