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

后端 未结 4 774
星月不相逢
星月不相逢 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:42

    Looking at your 'source' I would suggest the trick here is to set $/ - the record separator.

    If you set it to a single space, you can iterate word by word. And then use a range operator to determine if you're within delimiters.

    Example:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    local $/ = ' ';
    
    while (  ) {
       if (  m/START/ .. /END/ ) {
           s/bingo/okyes/g;
       } 
       print;
    }
    
    __DATA__
    xx START xx bingo xx bingo xx END xx bingo xx START xx bingo xx END bingo
    

    This prints:

    xx START xx okyes xx okyes xx END xx bingo xx START xx okyes xx END bingo
    

    You could probably accomplish this with a single regex. I'm going to suggest that you don't because it'll quite complicated and hard to understand later.

提交回复
热议问题