Preserving backslashes in Perl strings

Norbert picture Norbert · Apr 23, 2013 · Viewed 22.7k times · Source

Is there a way in Perl to preserve and print all backslashes in a string variable? For example:

$str = 'a\\b';

The output is

a\b

but I need

a\\b

The problem is can't process the string in any way to escape the backslashes because I have to read complex regular expressions from a database and don't know in which combination and number they appear and have to print them exactly as they are on a web page.

I tried with template toolkit and html and html_entity filters. The only way it works so far is to use a single quoted here document:

print <<'XYZ';
a\\b
XYZ

But then I can't interpolate variables which makes this solution useless.

I tried to write a string to a web page, into file and on the shell, but no luck, always one backslash disappears. Maybe I am totally on the wrong track, but what is the correct way to print complex regular expressions including backslashes in all combinations and numbers without any changes?

In other words: I have a database containing hundreds of regular expressions as string data. I want to read them with perl and print them on a web page exatly as they are in the database. There are all the time changes to these regular expressions by many administrators so I don't know in advance how and what to escape. A typical example would look like this: 'C:\\test\\file \S+' but it could change the next day to '\S+ C:\\test\\file' Maybe a correct conclusion would be to escape every backslash exactly one time no matter in which combination and in which number it appears? This would mean it works to double them up. Then the problem isn't as big as I feared. I tested it on the bash and it works with two and even three backslashes in a row (4 backslaches print 2 ones and 6 backslashes print 3 ones).

Answer

Grant McLean picture Grant McLean · Apr 23, 2013

The backslash only has significance to Perl when it occurs in Perl source code, e.g.: your assignment of a literal string to a variable:

my $str = 'a\\b';

However, if you read data from a file (or a database or socket etc) any backslashes in the data you read will be preserved without you needing to take any special steps.