如何防止Perl将双反斜杠解释为单反斜杠字符?

Oma*_*mar 3 perl

如何打印包含双反斜杠\\字符的字符串(单引号),而不会使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
Run Code Online (Sandbox Code Playgroud)

hob*_*bbs 10

Perl中唯一没有解释反斜杠的引用构造是这里单引号文档:

my $string1 = <<'EOF';
a\\\b
EOF
print $string1; # Prints a\\\b, with newline
Run Code Online (Sandbox Code Playgroud)

因为here-docs是基于行的,所以你不可避免地会在字符串的末尾添加换行符,但你可以删除它chomp.

其他技术只是简单地使用它并正确地反斜杠(对于少量数据),或者将它们放在一个__DATA__部分或外部文件中(对于大量数据).

  • @melpomene https://github.com/arodland/Syntax-Feature-RawQuote — `perl -Msyntax=raw_quote -le 'print r\`a\\b\\c\`' ` (3认同)

hob*_*bbs 7

如果你有点疯狂,并且喜欢使用实验软件与perl的内部结构来改善代码的美观,那么你可以在今天早上使用CPAN上的Syntax :: Keyword :: RawQuote模块.

use syntax 'raw_quote';
my $string1 = r'a\\\b';
print $string1; # prints 'a\\\b'
Run Code Online (Sandbox Code Playgroud)

感谢@melpomene的灵感.