my $found = 0; while (<$fh>) { if (match()) { $found = $.; last; } } if ($found) { seek($fh, $found, SEEK_SET); open(my $fh_tmp, '<', ...) or die; while (<$fh>) { transform(); print $fh_tmp $_; } replace_original_with_tmp(); }