Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Increasing key/values held in a Hash from an Array

by xdg (Monsignor)
on Mar 17, 2006 at 21:33 UTC ( [id://537588]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://537588]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-03-29 01:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found