in reply to Re: searching and replacing strings in a multi line variable
in thread searching and replacing strings in a multi line variable

Another little quibble. I would not pass a search/replacement pattern as a string; rather, as a  Regexp object as created by the  qr// operator. The reason is that  qr// m// s/// all speak the same language. Consider:

c:\@Work\Perl\monks>perl -wMstrict -le "for my $sr ('k\s', 'k\\s', 'k\\\\s', qr{ k \\ s }xms, qr{k\\s}xms) { my $s = 'remove back\slash'; printf qq{'$s' %s -> }, ref $sr ? $sr : qq{'$sr'}; $s =~ s{$sr}{xx}xmsg; print qq{'$s'}; } " 'remove back\slash' 'k\s' -> 'remove back\slash' 'remove back\slash' 'k\s' -> 'remove back\slash' 'remove back\slash' 'k\\s' -> 'remove bacxxlash' 'remove back\slash' (?^msx: k \\ s ) -> 'remove bacxxlash' 'remove back\slash' (?^msx:k\\s) -> 'remove bacxxlash'

Another advantage of using  Regexp objects to talk about regex patterns is precision of control. "The fact that the input is a multi-line string is not an issue..." except when it is. And the best time to consider this issue is at the point at which the regex is created, and perhaps in the context of the string against which you are matching.

c:\@Work\Perl\monks>perl -wMstrict -le "my $inputtext = qq{a multi line\nstring and\nanother line\nthing here +\n}; print qq{<<$inputtext>> \n}; ;; my $newText = replaceText($inputtext, qr{ lin .*? ing }xms, 'xx-xx'); print qq{<<$newText>>}; ;; sub replaceText { my ($inputText, $regex, $replacement) = @_; $inputText =~ s/$regex/$replacement/g; return $inputText; } " <<a multi line string and another line thing here >> <<a multi xx-xx and another xx-xx here >>
In this example, the multi-line match and replacement works as expected even though the  s///g substitution ultimately used has no  /s "dot matches all" modifier. No matter. The behavior of dot was determined and could be understood at the point of creation of the  Regexp object; the object could have been passed around endlessly and its behavior would not change. Of course, the same behavior could be achieved using a  'lin(?s:.)*?ing' string literal to define the pattern, but that just qives you a few more regex hoops to jump through. (And on a related note, Regex Best Practice dictates that all  qr// m// s/// operators should effectively have an  /xms tail IMHO.)


Give a man a fish:  <%-{-{-{-<