tilly is correct that
CGI.pm will solve these problems for you, however, you mentioned printing them to the Web. If this is for personal use with debugging, that's probably not an issue. However, if you are doing this for production, it's easy to open up a security hole here. For example, a person may be able to execute a server side include as the server's user. Not good.
Other issues allow them to include random HTML or other things that aren't intended. Read up on security issues to find out how to deal with some of these problems.
Cheers,
Ovid