I am filtering HTML pages and would like to bold every mention of the term 'Perl' in the body. Currently, I am doing this with the HTML::TreeBuilder module, as the following code demonstrates.

My question is: Is this the most effective/safest way to do this?

FYI, this code is actually being used in a HTML::Mason autohandler, in the filter section. In the real code, I put the return value back into $_, as required by Mason. Therefore, I can not use print statements or any other direct output from my process. This also ensures that I only change instances of perl that are text, not included in links, images, or other tags.

#! perl use strict; use warnings; use HTML::TreeBuilder; use HTML::AsSubs; undef $/; print processHTML(<DATA>); exit; sub processHTML { my $tree = HTML::TreeBuilder->new_from_content($_[0]); $tree->elementify(); my @body = $tree->look_down("_tag", "body"); for my $body (@body) { $body->objectify_text(); my @perl_parts = $body->look_down("_tag", "~text", sub {$_[0]->attr('text') =~ /perl/i} ); for my $perl_text ( @perl_parts ) { my @items = split(/(perl)/i, $perl_text->attr('text')); $_ = (/perl/i ? b($_) : $_) for @items ; $perl_text->replace_with(@items)->delete(); } $body->deobjectify_text(); } my $return = $tree->as_HTML; $tree->delete; $return; } __END__ <html> <head> <title>This title contains Perl but does not get changed.</title> </head> <body> <p>This is some text containing the term 'perl'.</p> <ol> <li>Unix</li> <li>Perl</li> <li>Linux</li> </ol> <p>Notice how the term perl in the following link doesn't change, but +the text does. <a href="http://www.perlmonks.org">Perlmonks.org</a></p> </body> </html>

In reply to Is this the best way to use HTML::TreeBuilder to bold text in an HTML document? by johannz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.