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

I am developing a module with a function that prints HTML to stdout. The function prints the standard "Content-type: text/html" before printing the HTML, assuming a CGI-like environment. The problem is that sometimes people are not using the module in a CGI script. The Content-type line shows up in the HTML and looks awkward in such cases.

So what to do? Here's one solution I came up with:

print "Content-type: text/html\n\n" if defined $ENV{'SERVER_SOFTWARE'} +;
But I am not sure if this is 100% foolproof. Is it?

Also, I am worried about something else: What if someone printed the header before using my function and then the header gets printed again when they use my function. The Content-type line would be printed within the HTML. How could I prevent this? Is there a way of checking if the header has already been sent?

Replies are listed 'Best First'.
Re: Printing content-type in the proper context
by johnnywang (Priest) on Dec 24, 2004 at 04:15 UTC
    I would put the html generating code as a separate function/module, then the caller can decide whether they want to print out the content-type or not.
      The function prints an entire HTML page. So I am inclined to put the header in the function. Plus, it's more simple for novice users to write:
      printHTML();
      Instead of using the CGI module and writing:
      print header, printHTML();
        HTML and HTTP headers are two different things, so it's a good idea to have them in separate functions. For lazy users, you can provide a wrapper third function which calls both:
        sub print_everything_with_extra_cheese { print header(); print printHTML(); }
        A reply falls below the community's threshold of quality. You may see it by logging in.