为什么PowerShell(使用Perl)在简单的print语句中删除双引号?

Cof*_*ter 6 powershell perl

我是一个长期的Linux用户,但我是Windows和PowerShell的新手.我刚刚第一次安装了Windows7和Strawberry Perl 5.我现在想用Windows PowerShell进行简单的命令行打印.

看起来Perl安装正确:

PS C:\Users\Me> perl -v 
This is perl, v5.10.0 built for MSWin32-x86-multi-thread Copyright
1987-2007, Larry Wall 
...

命令行的工作原理:

PS C:\Users\Me> perl -e 'die'
Died at -e line 1.

PS C:\Users\Me> echo 'print "Hello, World\n"' | perl
Hello, World

但是,当我单独尝试它时,它会打印一个文件处理程序警告:

PS C:\Users\Me> perl -e 'print "Hello, World\n"'
No comma allowed after filehandle at -e line 1.

所以看起来它删除了双引号.

PS C:\Users\Me> perl -e 'print \"Hello, World\n\"'
Hello, World

这可行,但它的丑!让我们再试一次:

PS C:\Users\Me> perl -e 'print qq{Hello, World\n}'
Hello, World

多数民众赞成,但我很困惑.

为什么PowerShell会在单引号中转义双引号?有PowerShell用户吗?

Bri*_*ter 4

我认为这里有几个问题。一是引号在 powershell 和 perl 中都具有象征意义。powershell 中的引号和转义工作方式与 UNIX shell 中的工作方式略有不同。在 powershell 中查看 man about_quoting 。

第二个问题是 perl 命令行在 Windows 上的行为有所不同。您想要传递给 perl 的命令行内的任何双引号都需要在 perl 术语中转义为 \"。这不是 powershell 特有的。这是 perl 在 Windows 上的工作方式。您通常会遇到类似的问题cmd.exe。

这些版本应该可以工作:

PS> & perl -e "print \`"hello, world\n\`""
hello, world
PS> $s = "print \`"hello, world\n\`""
PS> echo $s
print \"hello, world\n\"
PS> & perl -e $s
hello, world
Run Code Online (Sandbox Code Playgroud)

您可以使用单引号以更少的转义来完成相同的操作。

PS> & perl -e 'print \"hello, world\n\"'
hello, world
PS> $s = 'print \"hello, world\n\"'
PS> echo $s
print \"hello, world\n\"
PS> & perl -e $s
hello, world
Run Code Online (Sandbox Code Playgroud)

您还可以将换行符放入 powershell 中,而不是将换行符转义序列传递给 perl 进行解析。

PS> & perl -e "print \`"hello, world`n\`""
hello, world
PS> $s = "print \`"hello, world`n\`""
PS> echo $s
print \"hello, world
\"
PS> & perl -e $s
hello, world
Run Code Online (Sandbox Code Playgroud)