Version 4 of Here document

Updated 2008-01-28 16:05:28 by FB

{From the Wikipedia article [L1 ]:

"A here document (also called a here-document or a heredoc), is a way of specifying a string literal in shells such as Bash, Windows PowerShell and the Bourne Shell, as well as programming languages such as Perl, PHP, Python and Ruby. It preserves the line breaks and other whitespace (including indentation) in the text. Some languages allow variable interpolation or even code to be evaluated inside of the string."


EKB Since in Tcl, everything is a string, it seems to me that every Tcl program is a heredoc, of the sort that "allow(s) variable interpolation or even code to be evaluated inside of the string." To get a heredoc of the sort that doesn't have any interpolation or evaluation, use curly braces. For example, the sample Ruby code from Wikipedia,

 puts <<GROCERY_LIST
 Grocery list
 ------------
 1. Salad mix.
 2. Strawberries.*
 3. Cereal.
 4. Milk.*

 * Organic
 GROCERY_LIST

can be implemented this way:

 puts {Grocery list
 ------------
 1. Salad mix.
 2. Strawberries.*
 3. Cereal.
 4. Milk.*

 * Organic}

FB: Not really. A "pure" heredoc is format-agnostic. Your example will fail if your string includes an unbalanced brace, e.g.:

Ruby:

puts <<GROCERY_LIST
Grocery list }
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
 
* Organic
GROCERY_LIST

Tcl:

puts {Grocery list }
# everything below is a syntax error because of the above close brace.
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
 
* Organic}

So in Tcl you have several ways of specifying string litterals:

  • as single words; special chars need to be escaped;
  • between double quotes; special chars also need to be escaped;
  • between braces; braces must be balanced or escaped (in which case the backslash becomes part of the string, so it's not a real escape).

Tcl doesn't provide an heredoc like feature, because all quoting rules require the user to escape all significant characters. This is a need I tries to address in Cloverfield with the {data} word modifier (see Cloverfield - Tridekalogue, section Word modifiers, item Raw data). The above example becomes:

puts {data}GROCERY_LIST
Grocery list }
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
 
* Organic
GROCERY_LIST

which is very similar to the Ruby version. The real strength of heredoc is to let the user supply an arbitrary delimiter (here GROCERY_LIST) to circumvent the regular formatting rules.

BTW, the present Wiki provides heredoc-like markup with the six- and three-equal sign sequences (see Wiki formatting rules 6). Of course they are not real heredocs because one cannot use these sequences within the quoted text, but the concept is quite similar.