Since you get to know the filename in the loop, you could simply store your lines in a string, then write it at once when you exit the loop.
This is also much more efficient than opening the file each time for writing, also less prone to concurrency problems.
Example:
my $buffer = "first line\n";
foreach my $do (keys %doing) {
# DO DB query for $do where fo $do can be serveral bodylines;
$buffer .= $bodyline . "\n";
}
$buffer .= "last line\n";
# now you know the file name
open FILE, ">$name" or die "bla bla";
print FILE $buffer;
close FILE;
-- TMTOWTDI