[PATCH perlfaq6.pod] Explain \Q better

[email protected] (Mark Jason Dominus)
Newsgroups perl.perlfaq.workers,perl.perl5.porters
Organization Plover Systems
Message-ID <[email protected]>
The 'example' in perlfaq6 of the use of \Q is ineffective:


       Remember also that any regex special characters will be acted
       on unless you precede the substitution with \Q.  Here's an
       example:

           $string = "to die?";
           $lhs = "die?";
           $rhs = "sleep, no more";

           $string =~ s/\Q$lhs/$rhs/;
           # $string is now "to sleep no more"

       Without the \Q, the regex would also spuriously match "di".


It says 'the regex would also spuriously match "di"', and in some
sense that's true, but it's not true for the example.  Without the \Q,
the regex matches "die", not 'di'.

I suggest the following change, or something like it.  My idea here is
to present a typical example that gives the reader an idea of when \Q
would be useful, by producing an obviously garbled answer without \Q,
and a correct answer with \Q:

--- pod/perlfaq6.pod	2003/09/01 19:41:10	1.1
+++ pod/perlfaq6.pod	2003/09/01 20:12:09
@@ -292,14 +292,26 @@
 also that any regex special characters will be acted on unless you
 precede the substitution with \Q.  Here's an example:
 
-    $string = "to die?";
-    $lhs = "die?";
-    $rhs = "sleep, no more";
+    $string = "Placido P. Octopus";
+    $regex  = "P.";
 
-    $string =~ s/\Q$lhs/$rhs/;
-    # $string is now "to sleep no more"
+    $string =~ s/$regex/Polyp/;
+    # $string is now "Polypacido P. Octopus"
 
-Without the \Q, the regex would also spuriously match "di".
+Because C<.> is special in regular expressions, and can match any
+single character, the regex C<P.> here has matched the <Pl> in the
+original string.
+
+To escape the special meaning of C<.>, we use C<\Q>:
+
+    $string = "Placido P. Octopus";
+    $regex  = "P.";
+
+    $string =~ s/\Q$regex/Polyp/;
+    # $string is now "Placido Polyp Octopus"
+
+The use of C<\Q> causes the <.> in the regex to be treated as a
+regular character, so that C<P.> matches a C<P> followed by a dot.
 
 =head2 What is C</o> really for?
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.