use strict; use warnings; my $cnt=1; while (defined (my $first = ) and defined (my $second = ) ) { my $name1 = (split /\s+/, $first)[0] // last; # handle trailing my $name2 = (split /\s+/, $second)[0] // last; # potential "\n" blank lines print "$cnt\t$first"; if ($name1 ne $name2) { $cnt++; } print "$cnt\t$second"; } =prints 1 one 1 one 1 two 1 two 1 three 1 three 1 three 2 four note: same result with or without the trailing blank line =cut __DATA__ one one two two three three three four Odd line here followed by a blank line if you want