in reply to Re: Re: Counting text strings
in thread Counting text strings
But back to the way this:while (<FILE>) { $count += () = m/foo/g } print $count;
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).while (<FILE>) { while (/foo/g) { $count++; print "$count so far.\n"; } }
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:
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.)my $count; while (<FILE>) { if ( $count += s/foo/foo/g ) { print "$count so far\n" ) }
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Re: Re: Counting text strings
by vector40 (Initiate) on Mar 04, 2003 at 07:55 UTC |