Forum Moderators: coopster & phranque

Message Too Old, No Replies

Find the num of times a str appears in a file

Is this possible in Perl

         

AWildman

3:13 pm on Apr 5, 2004 (gmt 0)

10+ Year Member



What I need to know is if there is a way to find out the number of times a phrase appears in a file. I'm creating a site search and need to know this for frequency. I know its easy enough to find out of a phrase appears in a file, but how do you find out how many times it appears?

Added:

Let me say, I'd like to do this without searching the file for the first occurrance of the word, then splitting the file after the first occurrance,and then searching the rest of the file, and so on for each occurance.

VectorJ

4:39 pm on Apr 5, 2004 (gmt 0)

10+ Year Member



You could use something like:


while ($file =~ m/theword/g) {
$x++;
}

Still using matching, but at least there's no splitting. Don't forget the /g at the end of the regex.

AWildman

4:49 pm on Apr 5, 2004 (gmt 0)

10+ Year Member



I'll give that a whirl. Thank you very much!

DrDoc

7:58 pm on Apr 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$text = "foo bar baz foo widgets foo foo";
@count = ($text =~ /foo/g);
print ($#count + 1);

...will print 4

DrDoc

8:03 pm on Apr 7, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can also do:

$text = "foo bar baz foo widgets foo foo";
$count = @{[$text =~ /foo/g]};
print $count;

AWildman

8:05 pm on Apr 7, 2004 (gmt 0)

10+ Year Member



Awesome! I'll try that too. Thanks a bunch.