in reply to counting words in string
There Is More Than One Way To Do It :-)
The method you showed is fine. If the input string starts getting long, you might have to watch out for memory usage. Here's a version that uses a regex and a while loop to scan the string, without building an intermediate @names array. I'm using the regex \S+ (one or more non-whitespace characters) to match "names", so that this code should produce the same output as yours regardless of the input string. If you need to match only certain characters in the names, you'd have to tell us more about that (Re: How to ask better questions using Test::More and sample data).
use warnings; use strict; use Test::More tests=>1; my $str = "iowq john stepy andy anne alic bert stepy anne bert andy st +ep alic andy"; my %names; pos($str)=undef; while ($str=~/\G\s*(\S+)(?:\s+|\z)/gc) { $names{$1}++; } die "failed to parse \$str" unless pos($str)==length($str); is_deeply \%names, { alic => 2, andy => 3, anne => 2, bert => 2, iowq => 1, john => 1, step => 1, stepy => 2 };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: counting words in string
by frazap (Monk) on Aug 08, 2018 at 14:26 UTC | |
by haukex (Archbishop) on Aug 10, 2018 at 21:44 UTC |