eskay has asked for the wisdom of the Perl Monks concerning the following question:

Greetings,
I need to perform a search and replace in a file that has delimiters START and END.
START and END could be on separate lines or the same line.
In addition, if the pattern between START and END has a word with a \ in front of it, for e.g,

START This is the line I need to \change END

then the search and replace do not apply to \change.
Let me provide an example. Let the name of the file be filein, which contains -

I am IntErEsted in making changes to the following lines.
However, START thE chAnges mUst bE \CME madE hErE. END
There may be cases whErE
START chAngEs nEEd to be mAdE hErE
tOO. END

In the above paragraph, I need to do a search and replace in between START and END.
What I am looking for is

I am IntErEsted in making changes to the following lines.
However, START the changes must be \CME made here. END
There may be cases whErE
START changes need to be made here
too. END

Thank you in advance for your help.
eskay

Replies are listed 'Best First'.
Re: A newbie's question in regex
by BrowserUk (Patriarch) on Mar 23, 2010 at 19:13 UTC
    $text = <<'EOT'; I am IntErEsted in making changes to the following lines. However, START thE chAnges mUst bE \CME madE hErE. END There may be cases whErE START chAngEs nEEd to be mAdE hErE tOO. END EOT ;; $text =~ s[START(.+?)END]{ 'START' . join('', map{ /^\\/ ? $_ : lc } split /(\s+)/, $1 ) . 'END' }smge;; print $text;; I am IntErEsted in making changes to the following lines. However, the changes must be \CME made here. There may be cases whErE START changes need to be made here too. END

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: A newbie's question in regex
by AnomalousMonk (Archbishop) on Mar 24, 2010 at 06:30 UTC

    An approach using nested substitutions is also possible, but there may be a bit too much double-negation going on here for comfort.

    use warnings; use strict; my $text = <<'EOT'; I am IntErEsted in making changes to the following lines. However, START thE chAnges mUst bE \CME madE hErE. END There may be cases whErE START chAngEs nEEd to be mAdE \CME hErE tOO. END EOT $text =~ s{ (?<= START) (.*?) (?= END) } { (my $replacement = $1) =~ s{ (?<! \S) ([^\s\\] \S*) } { lc $1 }xmsge; $replacement; }xmsge; print qq{[[$text]] \n\n};
    [[I am IntErEsted in making changes to the following lines. However, START the changes must be \CME made here. END There may be cases whErE START changes need to be made \CME here too. END ]]

    Good luck with the homework.