views:

193

answers:

3

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.

A: 

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

See the perlop man page.

pavium
+7  A: 

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.

Ether
I thought about that one, too! For some reason I thought it would still interpolate the backslashes. Stupid Python making me mix up my string interpolation. (The only note to add to this answer is that this adds a possibly undesirable addition of a newline to the end of the data.)
Chris Lutz
@Chris: indeed, in which case a `substr()` or `chomp()` will fix it up nicely.
Ether
Don't forget, however, that you can escape the ' and \ even in single quoted strings. I should change the docs to note that. :)
brian d foy
+1  A: 

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.

Greg Bacon