I thought I understood this but my code is not working, and I am not sure why. I am trying to learn Perl on my own but it is a little frustrating, as there is not an abundance of clear, step-by-step material like with some other languages.
For this small script I wanted to be able to open a text file, and count how many times a word is found in that text file. This started as a kind of joke with a friend of mine, who types waaaay too many acronyms in his emails (lol wtf gtfo brb lmao etc)
So, my program was first written to search for lol, or LOL, and I copied one of his emails into a .txt file. It did not work so I tried something simpler; I made a small .txt file and typed a few randomish words and tried to count how many times 'the' appeared in the file. I got it to work, but it counts 4 when there are in fact 5. Can anyone please explain to me why it is getting the wrong number??
Thanks!! here is my code, followed by the text file I am using it with now:
For this small script I wanted to be able to open a text file, and count how many times a word is found in that text file. This started as a kind of joke with a friend of mine, who types waaaay too many acronyms in his emails (lol wtf gtfo brb lmao etc)
So, my program was first written to search for lol, or LOL, and I copied one of his emails into a .txt file. It did not work so I tried something simpler; I made a small .txt file and typed a few randomish words and tried to count how many times 'the' appeared in the file. I got it to work, but it counts 4 when there are in fact 5. Can anyone please explain to me why it is getting the wrong number??
Thanks!! here is my code, followed by the text file I am using it with now:
Code:
#!/usr/bin/perl
use strict;
print "Enter the name of your file, ie myfile.txt:\n";
my $val = <STDIN>;
chomp ($val);
my $cnt=0;
open (HNDL, "$val") || die "wrong filename";
while ($val = <HNDL>)
{
if ($val =~ /the/i)
{
print $val;
$cnt++;
}
}
print "Number of instances of 'the' found: $cnt\n\n";
close (HNDL);
Code:
the this the
a the- this is the
the then thee
thine thou thoust then