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; # handle leftover word.