Here's the error I get:
$ perl Countsample1.pl
syntax error at Countsample.pm line 14, near ")
my "
Global symbol "$word_count" requires explicit package name at Countsample.pm line 14.
Global symbol "$word_count" requires explicit package name at Countsample.pm line 18.
Global symbol "$word_count" requires explicit package name at Countsample.pm line 21.
Compilation failed in require at Countsample1.pl line 1.
BEGIN failed--compilation aborted at Countsample1.pl line 1.
Lines 13 and 14 are:
while(my $line=<>)
my $word_count;
Your while
loop needs a block of code. And blocks of code are delimited with braces. I think those lines (and the few following ones) should be:
my $word_count;
while(my $line=<>) {
my @words_on_line = split;
$word_count+= @words_on_line;
}
I've also moved my $word_count
outside of the loop - you really don't want to reset it to zero on each loop iteration, do you?
Hmm.. now when I run it it just hangs. What could be wrong? That usually means either an infinite loop or a program waiting for input.
In this case, it's the program waiting for input.
while(my $line=<>)
This reads from STDIN (ok, yes, actually it reads from either STDIN or the files which have been passed on the command line - but there weren't any in this example, so STDIN it is). Presumably, you want it to read from the filehandle that have just opened. So use that instead.
while(my $line=<IP>)
Now it doesn't hang. But it says that my test file contains 0 words. And that's wrong.
Ah the problem is here. my $line=<IP>
puts the line into $line
. But you split the line with just split
, which works on $_
, not $line
. Let's remove the my $line=
so that the while
loop puts the data into $_
.
while (<IP>)
Now the program says that my file contains 5 words. Which is better than zero, but probably not right. So there's likely to be a logic problem.
Now you start debugging you logic...
Update: Actually, no. My file did contain only five words. So the logic is sound. Time to start adding more features. And perhaps modernising your code - for example replacing your old-style open()
statement (open(IP,"test1.txt")
) with something more modern (open my $ip, '<', "test1.txt")
). Also check the return value from open()
- open my $ip, '<', "test1.txt") or die $!
.