http://qs321.pair.com?node_id=11137826


in reply to Re: Pattern matching in binary mode (I/O)
in thread Pattern matching in binary mode

Appreciated this comment, as it's one of the few useful things Google returned when searching for "perl sliding window string replace". I used it to make something similar that uses substr() instead of a regex, and bumps the buffer up if the search string is larger than the window size.

# note: only lightly tested, ymmv sub sliding_replace { my($srcfile,$dstfile,$search,$replace)=@_; if (! -e $file) { die("File [$file] does not exist\n"); } open(my $src,'<:raw',$srcfile); open(my $dst,'>:raw',$dstfile); my $winsize=4096; my $buf= ''; while(1) { my $bytecount=$src->sysread($buf, $winsize*2, length($buf)); while (1) { my $index=index($buf,$search); if ($index > 0) { substr($buf,$index,length($search),$replace); my $len=$index+length($replace); $dst->print(substr($buf,0,$len,'')); } else { $dst->print(substr($buf,0,$winsize,'')); last; } } last if $bytecount == 0; } # print any leftovers $dst->print($buf); $src->close(); $dst->close(); }