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
Split each line on START on END, keep a flag that tells you whether you are inside a range or not.
#!/usr/bin/perl
use warnings;
use strict;
my $inside;
while (<>) {
my @strings = split /(START|END)/;
for my $string (@strings) {
if ('START' eq $string) {
$inside = 1;
} elsif ('END' eq $string) {
undef $inside;
} elsif ($inside) {
$string =~ s/bingo/okyes/g;
}
print $string;
}
}
Or a bit shorter using a hash as a switch:
#!/usr/bin/perl
use warnings;
use strict;
use Syntax::Construct qw{ // };
my $inside;
while (<>) {
my @strings = split /(START|END)/;
for my $string (@strings) {
$inside = { START => 1,
END => 0,
}->{$string} // $inside;
$string =~ s/bingo/okyes/g if $inside;
print $string;
}
}