问题描述
如何打印包含双反斜杠 \\
字符的字符串(单引号),而不让 Perl 以某种方式将其插入到单斜杠 \
中?我也不想通过添加更多转义字符来更改字符串.
How can I print a string (single-quoted) containing double-backslash \\
characters as is without making Perl somehow interpolating it to single-slash \
? I don't want to alter the string by adding more escape characters also.
my $string1 = 'a\\\b';
print $string1; #prints 'a\b'
my $string1 = 'a\\\\b';
#I know I can alter the string to escape each backslash
#but I want to keep string as is.
print $string1; #prints 'a\\b'
#I can also use single-quoted here document
#but unfortunately this would make my code syntactically look horrible.
my $string1 = <<'EOF';
a\\b
EOF
print $string1; #prints a\\b, with newline that could be removed with chomp
推荐答案
Perl 中唯一一个完全不解释反斜杠的引用结构是这里的单引号文档:
The only quoting construct in Perl that doesn't interpret backslashes at all is the single-quoted here document:
my $string1 = <<'EOF';
a\\\b
EOF
print $string1; # Prints a\\\b, with newline
因为 here-docs 是基于行的,所以在字符串末尾不可避免地会出现换行符,但您可以使用 chomp
将其删除.
Because here-docs are line-based, it's unavoidable that you will get a newline at the end of your string, but you can remove it with chomp
.
其他技术只是简单地接受它并正确地反斜线您的字符串(对于少量数据),或者将它们放在 __DATA__
部分或外部文件中(对于大量数据).
Other techniques are simply to live with it and backslash your strings correctly (for small amounts of data), or to put them in a __DATA__
section or an external file (for large amounts of data).
这篇关于如何防止 Perl 将双反斜杠解释为单反斜杠字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!