in reply to How to use Substr to bulk substitutions?
Another example:
c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my $s = 'abXXcXXXXdefXXXXgXXhiXXXXXXXjkXX'; print qq{$s}; ;; my @off_len; while ($s =~ m{ X+ }xmsg) { push @off_len, [ $-[0], $+[0]-$-[0] ]; } dd \@off_len; ;; for my $ar_ol (reverse @off_len) { my ($off, $len) = @$ar_ol; substr $s, $off, $len, 'YYYYY'; } print qq{$s}; " abXXcXXXXdefXXXXgXXhiXXXXXXXjkXX [[2, 2], [5, 4], [12, 4], [17, 2], [21, 7], [30, 2]] abYYYYYcYYYYYdefYYYYYgYYYYYhiYYYYYjkYYYYY
Update 1: Deleted a useless my $len_s = length $s; statement left over from a previous iteration of the example code. Oops...
Update 2: Here's another example that uses an arbitrary replacement array:
Try removing YYY, then XXX, then FATHERS from the @repl array; try making this array empty. (Of course, it might be possible to integrate each offset/length array element pair with its replacement string in a single array, but I don't know the source of your data.)c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my $s = 'ab THE c RAIN def IN g SPAIN hi FALLS jk MAINLY l ON m'; print qq{$s}; ;; my @off_len; while ($s =~ m{ [[:upper:]]+ }xmsg) { push @off_len, [ $-[0], $+[0]-$-[0] ]; } dd \@off_len; ;; my @repl = qw(FOURSCORE AND 7 YEARS AGO OUR FATHERS XXX YYY); ;; my $least_i = $#off_len < $#repl ? $#off_len : $#repl; for my $rli (reverse 0 .. $least_i) { my ($off, $len) = @{ $off_len[$rli] }; substr $s, $off, $len, $repl[$rli]; } print qq{$s}; " ab THE c RAIN def IN g SPAIN hi FALLS jk MAINLY l ON m [[3, 3], [9, 4], [18, 2], [23, 5], [32, 5], [41, 6], [50, 2]] ab FOURSCORE c AND def 7 g YEARS hi AGO jk OUR l FATHERS m
Give a man a fish: <%-{-{-{-<
|
|---|