in reply to Counting between the lines

This is not tested:

my ($count, $word); while (<>) { $count++ unless /#/; # or maybe /^#/ would be better? if (/^# word (\d+)/) { # or \S+, etc. -- depending on what's +a valid word print "word $word\nnumber of text = $count\n" if defined $word +; $count = 0; $word = $1; } } print "word $word\nnumber of text = $count\n" if defined $word; # h +andle leftover word.

You can move the conditional output print to a function if duplicating the code bothers you.