How to perform search-and-replace within given $start-$end ranges?

后端 未结 4 797
星月不相逢
星月不相逢 2021-01-15 09:54

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 $patterns with the

4条回答
  •  耶瑟儿~
    2021-01-15 10:37

    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;
        }
    }
    

提交回复
热议问题