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

1.7k views Asked by At

What is the reasoning behind the name?

SS64 explains here strings in PowerShell as follows:

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 
'@ 
1

There are 1 answers

3
briantist On BEST ANSWER

They have this name in PowerShell because it is borrowed from Unix style shells, like many other elements and concepts in PowerShell:

From Wikipedia:

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

As for why that name was used originally, the article does not strictly cover etymology, but based on this description:

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.

It seems logical that the "here" part of the name refers to a file being included "here" (as in, at this point).


Just for completeness, it is worth noting that PowerShell also supports newlines directly in both single and double quoted [string]s, like so:

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

A better example of where a here-string is useful is when you need both types of quotes:

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

If that were just a single quoted string, the ' in grandma's would need to be escaped.

If it were a double quoted string, you'd need to escape the instances of " and you'd need to escape the $ if you didn't want variable expansion.


Interesting aside: the differences between how here-strings are interpreted form the basis of this demonstration of writing a bash/powershell/win batch polyglot (a script whose contents can be executed in any of those environments).