in reply to CGI: Premature end of script headers

Try inserting the following line between lines 2 and 3 of the code sample above:

$| = 1;
This will cause your output to be flushed immediately, rather than buffered (the default), which may help if an error is occurring and is arriving before the 'Content-type' header.

HTH.