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.


In reply to Re: Increasing key/values held in a Hash from an Array by xdg
in thread Increasing key/values held in a Hash from an Array by Gavin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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, details, 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, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.