while (my $matchingFiles = glob("*.rtsd001")) { ... my $seen_struct; while () { if ($seen_struct || /STRUCT20/) { $seen_struct = 1; print MODIFIED $_; } } ... }