You can do whatever you want before printing the header as just long as long as you don't print to STDOUT.

The first thing the webserver wants to see is a header, before it sends your page. If it doesn't then there is a problem. Everything sent out STDOUT goes to the webserver, so either print to STDOUT after the header or print to another file handle.
(I also recommend using the object interface of CGI)

Went to join the gridlock to see it
Held an eclipse party
Watched a live feed
I cn"t see tge kwubosd to amswr thus
I tried to see it, but 8000 miles of rock got in the way
What eclipse?
Wanted to see it, but they wouldn't reschedule it
Read the book instead