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 " $_"; } #### while (<>) { if (/^#ERRORS/ .. /^CELLS/) { push(@errors, $_); } elsif (/^CELLS/ .. /^\s*$/) { push(@errors, $_); } else { ...; # other processing } } print "Errors:\n"; for (@errors) { print " $_"; }