Say, a text file have many $start-$end
pairs, and within each pair there are some text. I want Perl to find-and-replace all $pattern
s with the
I find things like this are most simply done using the @-
and @+
built-in arrays in conjunction with substr
as an lvalue
$-[1]
contains the offset within the string where the first capture began, while $+[1]
contains the offset where it ended. Hence $+[1]-$-[1]
is the length of the captured section
This program finds all occurrences of /START(.+?)END/
and edits the captured section -- the region between START
and END
-- by applying a regex substitution to that substring
You may need to chnage this slightly depending on the real-world data that you're working with
use strict;
use warnings 'all';
use feature 'say';
my $str = 'xx START xx bingo xx bingo xx END xx bingo xx START xx bingo xx END bingo';
my ($start, $end, $pattern, $replacement) = qw/ START END bingo okyes /;
while ( $str =~ /\b$start\b(.+?)\b$end\b/gs ) {
substr($str, $-[1], $+[1]-$-[1]) =~ s/$pattern/$replacement/g;
}
say $str;
xx START xx okyes xx okyes xx END xx bingo xx START xx okyes xx END bingo