Perl q 函数或单引号不能正确 return UNC 路径的字符串文字

Perl q function or single quote doesn't return the string literal of UNC path correctly

Perl 的 q 函数或单引号应该 return 键入的字符串文字(\' 除外)。但对于以下情况,它不会按预期工作。 我想打印以下 UNC 路径

\dir1\dir2\dir3

所以我用过

my $path = q(\dir1\dir2\dir3); 

my $path = '\dir1\dir2\dir3'; 

但这会跳过前面的一个反斜杠。 所以如果我打印它,即 print $path; 它会打印

\dir1\dir2\dir3

我想知道为什么?我必须在 UNC 路径的开头键入 3 或 4 个反斜杠才能使其按预期工作。我错过了什么?

来自perldoc perlop

q/STRING/

'STRING'

A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.

变化:

my $path = q(\dir1\dir2\dir3);

至:

my $path = q(\\dir1\dir2\dir3);

至于为什么,这是因为 Perl 允许您通过使用反斜杠将引号分隔符包含在字符串中:

my $single_quote = 'This is a single quote: \'';

但是如果定界符前的反斜杠总是转义定界符,就没有办法用反斜杠结束字符串:

my $backslash = 'This is a backslash: \'; # nope

允许转义反斜杠也可以解决这个问题:

my $backslash = 'This is a backslash: \';

有趣的是,只有一种方法可以在 perl 字符串中输入双反斜杠,而不会将其插入为单个反斜杠。
正如所有其他答案所示,任何引号运算符都将反斜杠视为反斜杠,除非它后面直接有另一个。

让双反斜杠完全按照您输入的方式显示的唯一方法是使用 single quote here-doc.

my $path = <<'VISTA';  
\dir1\dir2\dir3 
VISTA
chomp $path;
print $path."\n";

会按照您输入的方式打印出来。