The previous poster is right in that this is not clean HTML. I also do not know whether you merely want to escape HTML entities, however, you might want to try
HTML::TreeBuilder to build a HTML parse tree and
HTML::Element, specifically the
as_HTML() sub, to output the HTML. You can use
as_HTML to escape HTML entities.
Johannes