为什么 "Here Strings" 被称为 "Here Strings"?

Why are "Here Strings" called "Here Strings"?

这个名字背后的原因是什么?

SS64 解释 PowerShell 中的字符串如下:

A here string is a single-quoted or double-quoted string which can span multiple lines. Expressions in single-quoted strings are not evaluated.

All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks.

$myHereString = @'
some text with "quotes" and variable names $printthis 
some more text 
'@ 

它们在 PowerShell 中有这个名称,因为它是从 Unix 风格的 shell 中借用的,就像 PowerShell 中的许多其他元素和概念一样:

From Wikipedia:

Here documents originate in the Unix shell, and are found in sh, csh, ksh, bash and zsh, among others.

至于为什么最初使用那个名字,文章并没有严格涵盖词源,而是基于这样的描述:

In computing, a here document (here-document, here-text, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace (including indentation) in the text.

名称的“此处”部分指的是“此处”包含的文件(例如,此时)似乎合乎逻辑。


为了完整起见,值得注意的是 PowerShell 还支持在单引号和双引号 [string] 中直接换行,如下所示:

$myString = 'some text with "quotes" and variable names $printthis 
some more text'

这里字符串有用的一个更好的例子是当你需要两种类型的引号时:

$myHereString = @'
some text with "quotes" and variable names $printthis 
some more text 
and my grandma's soup
'@ 

如果那只是一个单引号字符串,grandma's 中的 ' 需要转义。

如果它是双引号字符串,您需要转义 " 的实例,您需要转义 $如果您想要变量扩展。


有趣的是:here-strings 的解释方式之间的差异构成了 this demonstration of writing a bash/powershell/win batch polyglot(其内容可以在任何这些环境中执行的脚本)的基础。