So I'm working on a quick script that requires me to do some counting. The long and short of it is that I have some strings (generated elsewhere in the script) and I need to know how many newlines (for example) they contain. The canonical response (I've discovered) is to use
tr//:
$count = ($string =~ tr/\n/\n/);
Well, because there were other things I wanted to count I ended up using a similar construction with
s///g (did you know that
\s matches
\n for
m// and
s/// but not for
tr///? I didn't) which is where I get confused.
What do you expect the output from these to be:
# Greedy
$string = q(xxxx);
$count = ($string =~ s/x*/#/g);
print qq($string $count), $/;
# Not greedy
$string = q(xxxx);
$count = ($string =~ s/x*?/#/g);
print qq($string $count), $/;
I expected
# 1 and
#### 4. I got
## 2 and
######### 9. Excuse me? How's that again? 2 and 9? Color me confused.
Can anyone shed some light on this and maybe help me figure out how I can see what perl's doing to arrive at these numbers?
Note: I did figure out that my confusion stems from using * rather than + as modifier. Using + does give 1 and 4 (greedy vs. not-greedy) above. Whoops :) Even so, I'm still confused about the 2 and 9 from using star....