elbillaf
elbillaf

Reputation: 1994

Variable substitution in tcl

I'm running an incarnation of tcl 8.5 that has been embedded into another system. That system will accept and correctly execute a command such as:

uniformDist  minAndMax  {1 10}

where uniformDist is some object to which I do not have internal visibility.

I want to be able to say something like:

set M 1000
uniformDist  minAndMax  {1 M}

but this does not work. Nor does set M 1000 uniformDist minAndMax {1 $M}

I tried:

u minAndMax {1 [eval $M]}

and

u minAndMax {1 [eval M]}

Neither of those works.

The error message is:

expected a real value: unable to convert from: "$M"Error: expected fewer arguments [Error while parsing pair]

or

expected a real value: unable to convert from: "[eval"Error: expected fewer arguments [Error while parsing pair]

What is the right way that tcl does this?

Upvotes: 0

Views: 140

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13282

Variable substitution is expressed using $ and the variable's name (such as $M or ${M}).

This doesn't work:

uniformDist  minAndMax  {1 $M}

because the braces prevent substitution: $M is just the (sub)string 'dollar, upper case m'.

This works:

uniformDist  minAndMax  [list 1 $M]

because the arguments to list will be evaluated before the list {1 1000} is returned and passed to uniformDist.

The form "1 $M" would work too, and the command substitution [set M] can be used instead of the variable substitution above.

Documentation: Summary of Tcl language syntax

Upvotes: 3

Related Questions