in reply to Re: regex, find words that occur more than once.
in thread regex, find words that occur more than once.
Good synthesis, as GrandFather says. A couple of minor stylistic elements you might consider:
- You should put spaces around your Binding Operators. Regular expressions already look confusing to a lot of people. Same for before the parentheses of your for loop, but that's less of an issue.
- One might naively expect that the hash in question contains the counts, and you correct that right before output. That could be confusing if the two loops were more complex or separated by a lot of code. Rather than fixing it at the end, you could initialize the value to 1:
See Logical Defined Or and Assignment Operators for details on what I did there.while($text=~/\b(\w+)\b(?=.*\b\1\b)/g){ $words{$1} //= 1; # initialize empty value to one $words{$1}++; } - I usually name my hashes based upon how the key is related to the value. In this case, for example, %hits could be natural because when you look at it on the screen, you see the number of hits you got -- $hits{$word} reads to me as hits for word in English. On the other hand, %words sounds like I'm going to get words back, not a number. With that first change, it might be %count, %repetitions or %reps. Perl more than most programming languages is supposed to read following common grammar.
use strict; use warnings; use 5.10.0; my %reps; my $text = "and him him lad has him done and john has has"; while($text =~ /\b(\w+)\b(?=.*\b\1\b)/g){ $reps{$1} //= 1; $reps{$1}++; } foreach my $key (keys %words){ say "$key: $reps{$key}"; }
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: regex, find words that occur more than once.
by GrandFather (Saint) on Sep 15, 2020 at 21:25 UTC | |
by kennethk (Abbot) on Sep 15, 2020 at 23:28 UTC | |
by parv (Parson) on Sep 16, 2020 at 02:54 UTC |
In Section
Seekers of Perl Wisdom