snax has asked for the wisdom of the Perl Monks concerning the following question:
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:$count = ($string =~ tr/\n/\n/);
I expected # 1 and #### 4. I got ## 2 and ######### 9. Excuse me? How's that again? 2 and 9? Color me confused.# 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), $/;
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....
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regex (counting) confusion :(
by thinker (Parson) on Sep 18, 2003 at 14:05 UTC | |
|
Re: Regex (counting) confusion :(
by fletcher_the_dog (Friar) on Sep 18, 2003 at 14:25 UTC | |
by Abigail-II (Bishop) on Sep 18, 2003 at 14:40 UTC | |
by snax (Hermit) on Sep 18, 2003 at 14:51 UTC | |
|
Re: Regex (counting) confusion :(
by tcf22 (Priest) on Sep 18, 2003 at 14:31 UTC | |
|
Re: Regex (counting) confusion :( (link)
by tye (Sage) on Sep 18, 2003 at 15:21 UTC | |
|
Re: Regex (counting) confusion :(
by Abigail-II (Bishop) on Sep 18, 2003 at 14:33 UTC | |
|
Re: Regex (counting) confusion :(
by Anonymous Monk on Sep 18, 2003 at 14:24 UTC | |
by Anonymous Monk on Sep 18, 2003 at 14:36 UTC |