zsdc wrote:

Petri Rautakoski wrote:

I'm making a text replace and my text to search includes a metacharacter (.
The text to be searched has been stored in a scalar for example $search. The text where the search will be made has been stored for example in a scalar $text. Here is what I'm doing:


$search = "for example (this)";
$text = "looking for example (this)";
$toBeReplaced = "that";

$text =~ s|$search|$toBeReplaced|;

$text =~ s|\Q$search\E|$toBeReplaced|;


See: perldoc perlre

Hello Petri,


In Apocalypse 5 on Pattern Matching by Larry Wall, which is about what's wrong with regular expressions in Perl 5 and how are they going to look like in Perl 6, there is one part about the very problem with variables interpolation you've asked about and the klunky workaround I've sent you, which Larry himself considers to be one of the most important problems with Perl's regular expressions today. I thought you might be interested, so let me quote that part of Apocalypse 5:

: Too hard to match a literal string
:
: Since regexes undergo an interpolation pass before they're
: compiled, anything you interpolate is forced to be treated
: as a regular expression. Often that's not what you want,
: so we have the klunky \Q$string\E mechanism to hide regex
: metacharacters. And that's because...
:
: Two-level interpretation is problematic
:
: The problem with \Q$string\E arises because of the
: fundamental mistake of using interpolation to build regexes
: instead of letting the regex control how it treats the
: variables it references. Regexes aren't strings, they're
: programs. Or, rather, they're strings only in the sense that
: any piece of program is a string. Just as you have to work to
: eval a string as a program, you should have to work to eval a
: string as a regular expression. Most people tend to expect a
: variable in a regular expression to match its contents literally.
: Perl violates that expectation. And because it violates that
: expectation, we can't make $1 synonymous with \1. And interpolated
: parentheses throw off the capture count, so you can't easily use
: interpolation to call subrules, so we invented (??{$var}) to get
: around that. But then you can't actually get at the parentheses
: captured by the subrule. The ramifications go on and on.

From Apocalypse 5 by Larry Wall, 4 June 2002

http://dev.perl.org/perl6/apocalypse/5

--
ZSDC Perl and Systems Security Consulting


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>




Reply via email to