Oh my. Too much copypasting, too little abstraction, as Common Beginner Mistakes points out. For a good tutorial on CGI, see Ovid's excellent CGI course. Lastly, as has already been suggested, use templates to pull all that ugly HTML out of the script. My personal favourite is the shooting star, Template Toolkit 2.