# 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 = )) { 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