FreeKB - Escape any special character in Perl using quotemeta (\Q \E)
Escape any special character in Perl using quotemeta (\Q \E)

Home > Search
  by

There are a number of special characters that are used in regular expressions in Perl, such as * . ^ $. If you have a string of data that contains one of the special characters, it can be difficult to manipulate the string of data. This is most often found when attempting to replace the string of data. For example, let's say you've the following string of data.

my $foo = "b*r";

 

Printing foo will display the wildcard. 

b*r

 

However, let's say you attempt to replace the string of data.

$foo =~ s|b*r|Hello World|;

 

The result of this will be, which is most certainly not the expected result.

b*Hello World

 

The solution to this challenge is to escape the special characters.

$foo =~ s|b\*r|Hello World|;

 

While this is a reasonable solution when working with predicable, static data that will never change (which is extremely rare), this solution will fail when working with dynamic, unpredicable data. To handle this with dynamic, unpredictable data, the quotemeta operator can be used. The quotemeta operator will escape every special character in a string of data. \Q begins quotmeta and \E ends quotemeta. In this example, any special character in the $foo variable will be escaped.

my $foo = "\Qb*r\E";

 

Printing foo will now show that the wildcard character is escaped. 

b\*r

 

Or you can use \Q and \E in a replacement command to escape any special characters in the string being replaced.

$foo =~ s|\Qb*r\E|Hello World|;


Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments