my @if_stack; while (<$input>) { if (/$start/) { push @if_stack, $_; next; } if (/$stop/) { die unless @if_stack; pop @if_stack; next; } if (@if_stack) { # got a line which is inside a conditional } else { # got a line which is not inside a conditional print $output $_; } }