in reply to Count multiple pattern matches
As an efficiency note I'm not sure whether the pattern above keeps on getting recompiled. You may wish to benchmark a few variations. It is also possible that it is faster to match many times than it is to do one big complex match - I've certainly seen that happen in the past. And you should definitely look at Regexp::PreSuf.use strict; my @keywords=qw/foo bar 12345 abcd/; my $string = "foobarfoo1234523423412345abcdefsadfabc"; my %result; my $pattern = join "|", @keywords; while ($string =~ /($pattern)/ig) { $result{$1}++; } foreach my $s (keys %result){ print "$s=>$result{$s}\n"; }
As a bug note, if your strings are "foo", "bar", and "foobar", the original approach will correctly spot one of each in "foobar". This approach will not. (Depending on order it might spot "foobar" or it might spot "foo" and "bar".) This gets even more complicated if you're looking at things like "bazfoo" and "foobar".
|
---|