Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Word Count and Match

by davido (Cardinal)
on Jan 07, 2021 at 21:22 UTC ( #11126559=note: print w/replies, xml ) Need Help??

in reply to Word Count and Match

So... an adaptation of the code you presented works as you seem to want:

#!/usr/bin/env perl use strict; use warnings; my %count; my @words = qw(Bob Tom Dave John Jeremy Max Tom Harold Tom Bob Pete Pe +te Frank Tom); my $wordcnt='Bob|Tom|Dave|Tom|Bob|Dave'; foreach my $word (@words){ if($word=~/($wordcnt)/io){ $count{$1}++; } } print "$_ => $count{$_}\n" for sort keys %count;

This produces:

Bob => 2 Dave => 1 Tom => 4

There's no extra output with some total count.

Your problem would be a lot easier to diagnose if you supplied us with the following:

  • A small amount of sample data.
  • The smallest practical snippet of compilable code that we can run to demonstrate the failure you are seeing.
  • The sample output you desire, given the sample input provided.

Currently we're debugging code that probably isn't the code you are running, and we're only able to guess at what the data looks like.

I don't think you need the /o modifier for your regular expression; it doesn't do anything useful nowadays. And it's probably better to use $wordcnt = qr/Bob|Tom..../; instead regular quotes, though that's not strictly necessary. You should probably surround your pattern match with \b anchors for word boundaries so that you don't match "Bob" for the name "Bobby". Your alternation is also silly; what are repeated alternates supposed to do?

I scanned back through some of your previous posts over the past seventeen years; you've been asked to provide real code and sample input and output in the past.


Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2021-03-07 12:06 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (121 votes). Check out past polls.