Another way you could do this:
while (<FILE>) { $count += () = m/foo/g } print $count;
But back to the way this:
while (<FILE>) { while (/foo/g) { $count++; print "$count so far.\n"; } }
works is that the inner while will continue to evaluate $_ =~ /foo/g, (which is the lengthier version of: /foo/g ), anyhow it will continue to evaluate it until it has no more matches. So it will find the first foo then stop update the count, and then return to the search beginning where it left off, and so forth until it finds no more matches, but adding one to count each time it does find one. (I hope I am not confusing you further).

The if does not work because it only cares if the expression in the parens returns a true or false value. Strings with foo are true, add one to your count and on to the next line. (strings without foo are false of course). You could do something like the following:

my $count; while (<FILE>) { if ( $count += s/foo/foo/g ) { print "$count so far\n" ) }
Here the s/foo/foo/g returns the number of times it replaces foo with itself adds it to the count, and the number it returns is also the number the if checks for truth ( so a line like "foo foo foo" would be evaluated as if (3), as opposed to whether or not the addition to $count was successful.)

anyhow I hope I was some help, it is late and i tend to ramble anyhow.

oh yeah, ++ for asking for an explanation instead of just taking code without understanding it (and having to explain it often times makes me wonder if I understand it myself).

-enlil


In reply to Re: Re: Re: Counting text strings by Enlil
in thread Counting text strings by vector40

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.