开发者

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

开发者 https://www.devze.com 2022-12-17 23:24 出处:网络
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.What you\'re asking

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.


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';
blah@blah.blah.com\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.


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.


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

See the perlop man page.


Use the backslah two times,

print "This is a backslah character \\";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号