如何打印包含双反斜杠的字符串(单引号)\\
字符原样,而无需让 Perl 以某种方式将其插入单斜杠 \
?我也不想通过添加更多转义字符来改变字符串。
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 中唯一不解释反斜杠的引用结构是这里的单引号文档:
my $string1 = <<'EOF';
a\\\b
EOF
print $string1; # Prints a\\\b, with newline
因为 here-docs 是基于行的,所以在字符串末尾不可避免地会出现换行符,但您可以使用
chomp
将其删除。 .其他技术只是简单地接受它并正确地反斜线您的字符串(对于少量数据),或者将它们放入
__DATA__
部分或外部文件(用于大量数据)。
关于perl - 如何防止 Perl 将双反斜杠解释为单反斜杠字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331653/