Highlight a pattern found I made a small web application with a search box. I wanted to highlight the words found in the search.

foreach my $article (@{$search_articles}) {
    my @result;

    foreach my $word (split(' ', $article-&gt;{content})) {
        if ( $word =~ params-&gt;{search} ) {
            push(@result,
                '&lt;span style="background: yellow"&gt;' . $word . '&lt;/span&gt;');
        }
        else {
            push(@result, $word);
        }
    }

    $article-&gt;{content} = join(' ', @result);
}


It's a little wordy.  It is certainly possible to make cleaner, and I'd like to have your opinion.
Assuming that your search input is plain characters (i.e., no &lt;, &gt;, and likes), this is still problematic as can ruin your HTML code. Let's say I search for "border" in a page that contains &lt;table border="1"&gt;, or "class" in virtually any page written in the past 5 years,... IMO, this stuff is better done using a DOM parser and then searching just plain text.

Now, to comment the search itself... Let us assume that the word from your search box is contained in the variable $search. I think this is better done like this:

foreach my $article (@{$search_articles}) {
    $article-&gt;{content} =~ s/\Q$word\E/&lt;span style="background: yellow"&gt;$&amp;&lt;\/span&gt;/g
}