my $getPatterns; while (<>) { if (/^#ERRORS/ .. /^CELLS/) { push(@errors, $_); $getPatterns = 1; next; } elsif (defined $getPatterns) { push(@errors, $_); $getPatterns = undef if (/^\s*$/); next; } ...; # other processing } print "Errors:\n"; for (@errors) { print " $_"; }