I'd prefer using a hash, but since you didn't say how big your input files could be and apparently don't need to store the data for any further use, your approach of processing it line by line is just fine. What you have is close - just move a few of the variables around and that should about do it. Here is one way (it's not as elegant as a hash, but it is more like your original code)(tested):
# use the actual error for open open(FILE, $filename) || die "Error opening $filename: $!"; my ( $word, $count ); # move these out of the loop while (defined ($line = <FILE>)) { if ($line =~ /^# word (\d+)/) # tighten up regex a bit { if( defined $word ) { # print the results for the previous block print "the word number is: $word\n"; print "number of text = $count\n"; } $word = $1; $count = 0; } elsif ($line !~ /#/) { $count++; } } # print the results for the last block of data before eof print "the word number is: $word\n"; print "number of text = $count\n"; ** output from your example data ** the word number is: 26871 number of text = 3 the word number is: 26872 number of text = 2
Good job using warnings, but you should also use strict.
Update: I see gaal beat me to the punch. I guess that's what I get for testing... ;)
In reply to Re: Counting between the lines
by bobf
in thread Counting between the lines
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |