Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Nicolas Vautier wrote:
> Let's say that I have this:
> $line =~ s/$pattern/$replacement/;
> It should find every $pattern in $line and replace it by $replacement
> right?

   No.  It will replace only the first occurrence of $pattern (if at
least one exists) with $replacement.  To replace every occurrence, use
the /g switch, like this:

      $line =~ s/$pattern/$replacement/g;

> But since I have characters such as "|", """, "'", "!", "?"
> in my strings, it has a very strange behavior.
> Is there any way to specify perl NOT TO USE regular expressions
> expressions in my example?

   Yes.  Others posters have (correctly) said:

      $line =~ s/\Q$pattern\E/$replacement/;

but you can also "backslash" the special characters (like "|", """,
"'", "!", "?") with the quotemeta() function.  This function will
return a new pattern that you can use that has all the special
characters escaped (so that they won't interfere with the regular
expression matching).  You use it like this:

      my $escapedPattern = quotemeta($pattern);
      $line =~ s/$escapedPattern/$replacement/g;

   In other words, if you have the line:

      print quotemeta("Again? (y/n)");

you'll see the output:

      Again\?\ \(y\/n\)

meaning that if you use that output in a pattern match, the "?", "(",
and ")" characters won't affect how you match a pattern.

   Note that, according to "perldoc -f quotemeta", the line:

      my $escapedPattern = quotemeta($pattern);

is equivalent to:

      my $escapedPattern = "\Q$pattern\E";

which makes the following regular expression substitutions equivalent:

      my $escapedPattern = quotemeta($pattern);
      $line =~ s/$escapedPattern/$replacement/g;

      $line =~ s/\Q$pattern\E/$replacement/g;

   Which method should you use?  In my opinion, you should use
whichever one you find more readable and easier to understand.  And of
course, that part depends on you.

   I hope this helps, Nicolas.

   -- Jean-Luc

Site Timeline