my $add_at_end; while () { $add_at_end = 1 unless s/str1/str2/; print OUT; } print OUT "text" if $add_at_end;