my $insection = ""; while () { if (/^PITCHING/) { $insection="pitching" } if (/^DOUBLE\s+PLAYS/) { $insection="double plays" } if(defined($oldsection) && $insection ne $oldsection) { undef $oldsection; } elsif (defined($oldsection) && $insection eq $oldsection) { #print the HTML forms here } elsif ($insection && !defined($oldsection)) { $oldsection = $insection; next; } }