andyram27 has asked for the wisdom of the Perl Monks concerning the following question:

Ok, apache's giving me a premature end of script error. I know I have to print content headers before anything else, but I need to write to a file before I can display my page. Obviously, printing content headers Before my file i/o results in nothing getting displayed. Here's some code:
open(FH,">$data"); print FH "redrush\n"; close(FH); #the script is dependent on the contents of $data #I HAVE to do it this way, i can't just pass a string for reasons that + are unrelated to my question. some_command($data); &show_html; sub show_html { print header; #static html }
how to I write to file and then print content headers ??? is there some fwrite() function or something that could accomplish the same task without having to call print? please help.
thx,andy

Replies are listed 'Best First'.
Re: Premature end of script headers (i know, i know...)
by jasonk (Parson) on Mar 05, 2003 at 16:18 UTC

    The problem isn't that you have to do the headers before you do anything, it's that you have to print the headers before you print anything else to STDOUT. What is probably happening is that some of your earlier code is producing an error message, which is causing the headers to end early. Try using use CGI::Carp 'fatalsToBrowser'; which will cause the script to generate headers on demand if there is an error, so the error message will be visible in your browser, and check apache's error log to find out what the error message is that is being produced.

Re: Premature end of script headers (i know, i know...)
by OM_Zen (Scribe) on Mar 05, 2003 at 16:40 UTC
    Hi ,

    The print header; has something to do with writing to the STDOUT and using print FILEHANDLE ""; is something you do not to the STDOUT . Check for the file open status with some Carp(FatalsToBrowser) or through commandline execution
    use CGI::Carp 'fatalsToBrowser'; open (FH , ">$data) || die "The file is not opened for processing + : $!";


    The Carp method directs the errors to the webpage or just try running it through commandline option like showtheerrors.cgi NAME=VALUE but the Carp is a better way to do

Re: Premature end of script headers (i know, i know...)
by Jaap (Curate) on Mar 05, 2003 at 16:18 UTC
    You can print "Content-type: text/html\n\n"; first and then do your file printing and html outputting. That should work.
    Perhaps something is trying to write to STDERR before you do the show_html which causes the premature... error