in reply to Increasing key/values held in a Hash from an Array

I'd reverse the nature of the hash and store lines as keys and values as the count.

use strict; use warnings; my @words = qw( alpha beta gamma ); my @lines = ( 'alpha comes before beta and gamma, but not alphabet', 'beta comes after alpha; beta comes before gamma', 'gamma is the last word', ); my %count; for my $line ( @lines ) { for my $word ( @words ) { my $c =()= ($line =~ m/\b\Q$word\E\b/g); $count{$line} += $c; } } print map { "$count{$_}: $_\n" } @lines;

Gives:

3: alpha comes before beta and gamma, but not alphabet 4: beta comes after alpha; beta comes before gamma 1: gamma is the last word

(I'm sure this can be golfed, but I think it's clearer this way.)

Update: reading ikegami's answer, we're both on the right track, but I think solving slightly different problems. I'm not sure which one is the one you want: a count of occurances of keys across all lines or a count of occurances of keys within lines. And do you want to count multiple occurances of each special word? My answer gives the count by line including multiple occurances.

Also, it reminded me to add \Q and \E for safety's sake, so I've made that change.

Update 2: For those who don't recognize it, see Perl Idioms Explained - my $count = () = /.../g.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.