0

I am a newbie in TCL Programming. I was having confusion about curly braces, answer to this question tcl curly braces cleared most of my doubts. I can understand $var, {var}, and {$var}, But recently I came across another use of curly braces, ${var}. How is this interpreted by TCL? I have seen this is used when accessing variables in namespaces when namespaces name is in variable.

for example:

set x myNamespace   ;#myNamespace is name of namespace 
puts [set ${x}::var1] ;#var1 is variable in the namespace

It gives error when you don't use curly braces around 'x'.

And I also don't understand the difference between {a b c} and [list a b c], what is the difference in result of interpretation of these two commands by TCL interpretation.

elaborated explanation would be highly appreciated.

Community
  • 1
  • 1
Omsai Jadhav
  • 134
  • 10
  • 2
    [Related](http://stackoverflow.com/q/21387543/1578604). The question is not phrased the same, but the main underlying issue is. Also, I also explained the braces [in this recent answer](http://stackoverflow.com/a/22332741/1578604) at the bottom. – Jerry Mar 12 '14 at 12:35

1 Answers1

4

See rule 8 of the manual. It allows you to have variable names that might get mis-interpreted. For instance:

% set dotted.name 1
1
% puts $dotted.name
can't read "dotted": no such variable
% puts ${dotted.name}
1

Read section 8 carefully as it actually explains all this quite explicitly.

Update to answer edited question

In the example you provide using a namespace name in a variable you must consider section 8 part 1: a variable name includes letters, digits, underscores and namespace separators. This means that x::var1 is a valid variable name. So $x::var1 will attempt to dereference the var1 variable in the x namespace. As this is not what you meant, you must dereference your x variable separately. There are two ways to do this. You can either use the set command or the dollar operator.

set x myNamespace
puts [set ${x}::var1]
puts [set [set x]::var1]

The two puts statements are equivalent here with the second version showing an explicit separate pass to obtain the value of the x variable which is then substituted into the expression for the outer set command. The same occurs in the first version but just uses the grouping operator to restrict the effect of the dollar to the x variable name.

patthoyts
  • 32,320
  • 3
  • 62
  • 93
  • But why it is not working without braces in the code I have mentioned in the question? I don't have dot in the namespace name. Thanks! – Omsai Jadhav Mar 12 '14 at 12:47
  • 2
    If you remove the curly braces then you're effectively doing `[set ${x::var1}]`. In a way, it's the opposite of the dot problem in that tcl recognize `::` as a variable name character and therefore interprets the whole `x::var1` as a single variable name. – slebetman Mar 16 '14 at 05:16