my_question
my_question

Reputation: 3235

white space in un-braced expression

An interesting encounter:

set v "\{a b\}"
expr $v eq \{a b\}

The expression command returns true as expected. But the following also returns true:

set v "\{a b\}"
expr $v eq \{a      b\}

Basically the number of white spaces between \{a and b\} are ignored.

I know TCL expression should brace the arguments.

I know nobody would write such code seriously.

I can also guess what is going on:

  1. At script level parsing, the white spaces are simply used as word separation, one or more white spaces have same effect.
  2. When it comes to command expr, it has no access to the "raw" script, all it knows are there are 2 words, {a and b}, separated by some whitespace
  3. So just one white space is used.

But from the point of view TCL as a programming language, is it a bug?

Upvotes: 2

Views: 287

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13252

The third rule of Tcl syntax says

Words of a command are separated by white space (except for newlines, which are command separators).

(Command names and argument strings are words.)

The first clause in the documentation for expr says

Concatenates args (adding separator spaces between them)

So what happens is that the Tcl parser breaks up the string expr $v eq \{a b\} into five words, discarding the whitespace characters between them. Then the expr command concatenates its four arguments into a single string with a single separator space between each pair.

It’s basically the same thing as you see when you perform a list mutation command on a string:

% set a {a    b c}
a    b c
% lappend a d
a b c d

Documentation: expr, Summary of Tcl language syntax

Upvotes: 2

Related Questions