user10678532
user10678532

Reputation:

How to paste literal words in Tcl

Is there any syntax trick / feature which would allow me to paste two literal words in TCL, e.g. to concatenate a braced ({..}) word and a double-quoted "...") word into a single one?

I'm not asking about set a {foo}; set b "bar\nquux"; set c $a$b or append a $b -- I know about them; but about something without intermediate variables or commands. Analogous to the {*}word (which turns a word into a list).

I guess that the answer is "no way", but my shallow knowledge of Tcl doesn't allow me to draw such a conclusion.

Upvotes: 0

Views: 254

Answers (3)

Donal Fellows
Donal Fellows

Reputation: 137597

There's no way to do what you're asking for without a command, since the syntax of braced words doesn't permit anything before or afterwards, and once you have several words you need to join them with a command (because that's what commands do from the perspective of Tcl's language core; take some values and produce a value result). Not that having braces in the middle of a string is syntax error — it isn't — but it does stop them being quote characters. To be clear:

  1. puts a{b} prints a{b} because { is not special in that case and instead becomes part of the value.
  2. puts {a}b is a syntax error. (The only exception to this is {*}, which started as {expand} but that was waaaay too wordy.)

Approaches that work:

  • Use string cat.
  • Use a concatenation procedure (e.g., proc strcat {a b} {return $a$b}
  • Put both values inside the braces so it is a combined literal. Which only works if you have both parts being literals, of course.
  • Convert the braced part to non-braced (and non-double-quoted) form. This is always possible as every braced string has a non-braced equivalent, but can involve a lot of backslashes.

Upvotes: 0

Schelte Bron
Schelte Bron

Reputation: 4813

If you are using a recent Tcl version (8.6.2 or newer) you can use

set c [string cat {foo} "bar\nquux"]

For older versions, you can resort to

set c [format %s%s {foo} "bar\nquux"]

Upvotes: 2

Brad Lanam
Brad Lanam

Reputation: 5723

If your word is a valid list, you can do:

set orig {abc def}
set new [join $orig {}]

Upvotes: 0

Related Questions