The typical method is to dynamically build an alternation RE and let the RE engine do all the optimisation and hard work in lovingly hand optimised C. We use qr// so the RE is compiled once and avoid vast numbers of hash lookups, functionally useless variable assignments*, and RE compiles that you are doing above. As a general rule loops are great territory for optimisation due to the repeated execution of the loop code.
my @terms = qw( foo bar baz fool foolish );
my $re = join '|', map{quotemeta} sort {length($b)<=>length($a)}@terms
+;
$re = qr/($re)/;
while(<DATA>){
my @matches = $_ =~ m/$re/g;
next unless @matches;
print "Got @matches\n"
}
__DATA__
Only a foobar foolish fool
skips the sort by length
Without this foo you look foolish
and may match short elements!
Hash lookup tables may still have a place to convert a matched value into something else. Here is a trivial example. Beware /i as you need to lc($1) and use all lowercase keys in %terms or you won't get a match/lookup.
my %terms = ( foo => 'FOO', bar => 'BAR' );
my $re = join '|', map{quotemeta} sort {length($b)<=>length($a)}keys %
+terms;
$re = qr/($re)/i;
while(<DATA>){
s/$re/$terms{lc($1)}/g;
print;
}
__DATA__
foo is a word
Bar ba blacksheep
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|