use constant BLOCKLENGTH => 32768; # > length of any tag $\ = \BLOCKLENGTH; my $buffer = ''; while (!eof()) { $buffer .= <>; s/tag1/\n/g; s/tag2/\t/g; # leave BLOCKLENGTH chars in $buffer, # print however much comes before that print substr($buffer, 0, -BLOCKLENGTH, ''); }; # print whatever's left print $buffer;