Bootstrap FreeKB - Perl (Scripting) - Escape special characters using quotemeta (\Q \E)
Perl (Scripting) - Escape special characters using quotemeta (\Q \E)

Updated:   |  Perl (Scripting) articles

There are a number of special characters that are used in regular expressions, such as * . ^ $. 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|;

 

Following is the result, 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|;

 

Be aware that quotmeta will also escape whitespace and special characters, so you may end up with a lot of escapes when using quotmeta.

A\ quick\ brown\ fox\ jumps\ over\ the\ lazy\ dog\.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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