in reply to Re^2: counting words in string
in thread counting words in string
pos($str)=undef;
Note: This may seem like overkill in the simple example I showed, but it might become important if the code is copy and pasted into a larger script, where it's possible that a previous regex operation on $str left its pos set (but we want to start matching at the beginning of the string).
Where is the /c modifier documented in the perldoc ?
Hm, you're right that the doc seems a little hard to find. There's a pretty good explanation in perlretut's "Global Matching", and a more complex example of the usage of m/\G.../gc in perlop under "\G assertion".
How comes that I have to remember pos $str in the second loop ?
That would be the effect of the /c modifier: your second loop ends when the regex fails to match. The regex failing to match also resets pos, except when /c is used.
Are the two loops equivalent or will the second one failed in some situation ?
The way you've written it, no, because \w+ is not the same as \S+: the latter will match any non-word characters too, anything except \s characters.
If I change your loop's regex to /(\S+)/g, you can get the "failed to parse $str" error, namely when there's whitespace at the end of $str. This is because the last match doesn't reach all the way to the end of the string, while the regex I showed does, because it includes a \s+ after the \S.
The pos==length check makes sense if you want to make sure your loop went all the way to the end of the string and there's no garbage left at the end that we didn't match, but in this case, the only thing that could possibly be left after matching \S+ is whitespace, which we're not interested in.
searching a simpler loop
I showed the m/\G.../gc technique because I wanted to demonstrate it - it's a great tool for certain types of parsing (one example in the first paragraph of this post, or this), but as long as the OP just wants to split on whitespace, it's admittedly overkill. If you wanted to simplify the loop, you could say this (others have shown variations of this):
my %names; while ($str=~/(\S+)/g) { $names{$1}++; }
But as soon as the matching rule isn't as simple as \S+, things can get tricky. For example, if the rule is \w+, and the input string is " foo bar *", anything that looks for \w+ only will miss the junk at the end of the string.
|
|---|