http://qs1969.pair.com?node_id=1049101


in reply to Better way of doing!

G'day Xhings,

That's not a good way to write your code at all. There's no correlation between $i, ..., $o and the elements in @patterns that each is associated with. You have to write separate code for every single one of those. It scales exceptionally poorly: what happens if need to add another keyword? What you really want is a hash whose keys are the keywords and values are the count.

There's other problems as well in the while loop: you only count the first occurrence of the first keyword in each line; the smartmatch operator (~~) is experimental and unsuitable for production code.

Here's some skeleton code you can use as a basis for rewriting your script:

$ perl -Mstrict -Mwarnings -le ' my @eachline = ( "transaction blah find blah blah think blah save_param", "start_sub blah url blah blah submit transaction blah find" ); my @keywords = qw{transaction find think save_param start_sub url +submit}; my $pattern = join("|" => map { "(?<$_>\\b$_\\b)" } @keywords); my %count; for (@eachline) { while (/$pattern/g) { ++$count{(keys %+)[0]}; } } print "No. of matches for $_ is $count{$_}" for @keywords; ' No. of matches for transaction is 2 No. of matches for find is 2 No. of matches for think is 1 No. of matches for save_param is 1 No. of matches for start_sub is 1 No. of matches for url is 1 No. of matches for submit is 1

See perlre if you're unfamiliar with named capture groups, i.e. (?<name>pattern).

Update: Reviewing this code on the following day, I think named capture groups was probably overkill in this situation. Here's a simpler version using ordinary captures:

$ perl -Mstrict -Mwarnings -le ' my @eachline = ( "transaction blah find blah blah think blah save_param", "start_sub blah url blah blah submit transaction blah find" ); my @keywords = qw{transaction find think save_param start_sub url +submit}; my $pattern = "(" . join("|" => map { "\\b$_\\b" } @keywords) . ") +"; my %count; for (@eachline) { ++$count{$1} while /$pattern/g; } print "No. of matches for $_ is $count{$_}" for @keywords; ' No. of matches for transaction is 2 No. of matches for find is 2 No. of matches for think is 1 No. of matches for save_param is 1 No. of matches for start_sub is 1 No. of matches for url is 1 No. of matches for submit is 1

-- Ken