in reply to Logic problem

Define $basepath and $filename outside of the loop.
my ($basepath, $filename, $first_written);
Inside the loop use something like:
$basepath = 'somewhere'; $filename=localtime; do {&write($firstline, $basepath, $filename), $first_written++} unless + $first_written; . . .
And after the loop $basepath and $filename will still have their values, so you can just call &write($lastline, $basepath, $filename)