Here’s how to break down a search string into uniq keywords and highlight them using HTML:
# user input
my $search_string = "I really really need this";
# highlighting, get the s _uniq_ keyword
# use grep() to make sure we skip short keywords
my @kw = grep {length($_) > 2} split /[^\w]/,$search_string;
# expected output: keyword1|keyword2|keyword3
my $regex_keys = join "|", sort keys %{{ map { $_ => 1 } @kw }};
$data =~ s!($regex_keys)!\1!ig;
print $data;
This obviously assumes you’ve received a line of text $data from a database of some sort.
The interesting part is:
keys %{{ map { $_ => 1 } @kw }}
… which creates an anonymous hash with all the elements of the array as keys with a dummy 1 value. The keys sub in turn returns the keys and since map would’ve overwritten any duplicate keys, they are now unique!
Cool right?