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....


In reply to Regex (counting) confusion :( by snax

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.