| Author |
search a text file for a word
|
|
| apax999@gmail.com 2006-10-02, 3:58 am |
| I need a simple script that just runs in DOS that asks a user for a
word, then searches a text file for that word. The print out is simply
how many times that word was found. I have this code, but the print
out is always 0. Any suggestions?
#!/usr/bin/perl
use strict;
open(FILE, 'test.txt');
my $count = 0;
print "Enter a word to search for: ";
my $word = <STDIN>;
while (<FILE> ) { for (split) { $count++ if /^$word$/ }}
close FILE;
print $count;
| |
| usenet@DavidFilmer.com 2006-10-02, 3:58 am |
| apax999@gmail.com wrote:
> I need a simple script that just runs in DOS that asks a user for a
> word, then searches a text file for that word. The print out is simply
> how many times that word was found. I have this code, but the print
> out is always 0. Any suggestions?
>
> my $word = <STDIN>;
When the user types a word and hits ENTER, both the word and the ENTER
(newline) are captured in the variable $word. You should chomp($word)
to remove the newline.
> while (<FILE> ) { for (split) { $count++ if /^$word$/ }}
You might prefer an approach as suggested by
perldoc -q substring
--
David Filmer (http://DavidFilmer.com)
| |
| apax999@gmail.com 2006-10-02, 6:59 pm |
| Thanks the chomp worked.
One last (hopefully quick) question... how can I make this case
insensitive?
| |
| Paul Lalli 2006-10-02, 6:59 pm |
| apax...@gmail.com wrote:
> One last (hopefully quick) question... how can I make this case
> insensitive?
Please quote some context when you post a reply. Thank you.
Add the /i modifier to the regular expression. That is, stick the
letter i right after the final slash.
Paul Lalli
|
|
|
|