sub binSubst { my( $infile, $outfile, $regex, $repl, $maxlen, $bufsiz )= @_; binmode($infile); binmode($outfile); $bufsize ||= 16*1024; my $buf= ''; # Read the next chunk, appending to any left-over bytes: while( sysread( $infile, $buf, $bufsize, length($buf) ) ) { $buf =~ s/$regex/$repl/g; # How much to write out, unless... my $end= length($buf)-$maxlen; # ... we matched after that point and so # should write upto the end of last match: $end= $+[0] if $end < $+[0]; # Write out what we can, removing it from the buffer: print $outfile substr($buf,0,$end,''); } # Write out any left overs: print $outfile $buf; }