kk.
kk.

Reputation: 687

How can I prevent Perl from interpreting \ as an escape character?

How can I print a address string without making Perl take the slashes as escape characters? I don't want to alter the string by adding more escape characters also.

Upvotes: 0

Views: 5129

Answers (4)

Sridharan Gopal
Sridharan Gopal

Reputation: 41

Use the backslah two times,

print "This is a backslah character \\";

Upvotes: 0

Greg Bacon
Greg Bacon

Reputation: 139631

Use single quotes. For example

print 'lots\of\backslashes', "\n";

gives

lots\of\backslashes

If you want to interpolate variables, use the . operator, as in

$var = "pesky";
print 'lots\of\\' . $var . '\backslashes', "\n";

Notice that you have to escape the backslash at the end of the string.

As an alternative, you could use join:

print join("\\" => "lots", "of", $var, "backslashes"), "\n";

We could give much more helpful answers if you'd give us sample code.

Upvotes: 1

Ether
Ether

Reputation: 53986

What you're asking about is called interpolation. See the documentation for "Quote-Like Operators" at perldoc perlop, but more specifically the way to do it is with the syntax called the "here-document" combined with single quotes:

Single quotes indicate the text is to be treated literally with no interpolation of its content. This is similar to single quoted strings except that backslashes have no special meaning, with \ being treated as two backslashes and not one as they would in every other quoting construct.

This is the only form of quoting in perl where there is no need to worry about escaping content, something that code generators can and do make good use of.

For example:

my $address = <<'EOF';
[email protected]\with\backslashes\all\over\theplace
EOF

You may want to read up on the various other quoting operators such as qw and qq (at the same document as I referenced above), as they are very commonly used and make good shorthand for other more long-winded ways of escaping content.

Upvotes: 7

pavium
pavium

Reputation: 15118

It depends what you're escaping, but the Quote-like operators may help.

See the perlop man page.

Upvotes: 0

Related Questions