in reply to Newbie Q:How do I compare items within a string?
Instead of splitting into an intermediate array, you can extract the word positions directly from a regex scan. It goes like this:
That hash gives you a reference to a sorted array of string positions for each word found. In scalar context, the referenced arrays give the word count.my $string = q(So anyway, I basically need to check now across my string whether any elements in my string are repeated, and if so, how many times. I've read alot about manipulating arrays, but they're all based on arrays that you create yourself, rather than arrays created by opening a textfile, so I'm not sure how to manipulate my array. Any help would be much appreciated.); my %positions; push @{$positions{lc($1)}}, pos() - length($1) while $string =~ /([A-Za-z']+)/g; { local $_; print "$_\t@{$positions{$_}}\n" for keys %positions; }
Another thing that gives you is that you get to say directly what a word character is, instead of defining what splits them. I used that to include contractions (while messing up any single-quoted passages).
After Compline,
Zaxo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Newbie Q:How do I compare items within a string?
by johngg (Canon) on May 09, 2006 at 09:16 UTC | |
by Zaxo (Archbishop) on May 09, 2006 at 09:35 UTC | |
by johngg (Canon) on May 09, 2006 at 10:23 UTC |