my $widgetsFound=0; my $databaseName; my $databaseSection; while( <> ) { if( /^DATABASE:/ ) { if( $databaseName ) { print $databaseName; print "Widgets found: $widgetsFound\n"; print $databaseSection; } $databaseName = $_; $databaseSection = ""; $widgetsFound = 0; } else { $databaseSection .= $_; } if( $something ) { $widgetsFound++; } } # print the last database section that was parsed if( $databaseName ) { print $databaseName; print "Widgets found: $widgetsFound\n"; print $databaseSection; }