2

The question is about TCL Arrays. In my TCL script, variable1 is a variable value obtained from other functions(value is something like PATH_xyz.) variable2 is another variable obtained from other calculations, whose value is something like {3.5400 7.3200}.

I want to:

set ${variable1}(modifyPt) {variable2}

puts ${variable1}(modifyPt)

How to do it correctly?

I tried

set ${variable1}(modifyPt) $variable2

output>>>: 4379.2160 13892.8270

puts ${variable1}(modifyPt)

output>>>: PATH_62_5474(modifyPt)

(PATH_62_5474 was stored in variable1 at that point of execution) I was expecting value of PATH_62_5474(modifyPt), i.e., 4379.2160 13892.8270 at the second output above. also I tried

puts ${${xysp}(modifyPt)}

output>>>: Error: can't read "${variable1": no such variable

2 Answers 2

3

I'd recommend staying away from dynamic variable names. You can create a "compound" array key to keep it simple

# setup
set variable1 PATH_xyz
set variable2 {3.5400 7.3200}

# store the data in an array named "data"
set data($variable1,modifyPt) $variable2

# extracting it
% puts $data($variable1,modifyPt)    ; # => 3.5400 7.3200

# print the array contents
parray data    ; # => data(PATH_xyz,modifyPt) = 3.5400 7.3200

You can use a dictionary with a dynamic variable name, but extracting data from the dictionary looks a bit weird:

# store an empty dictionary in the variable "PATH_xyz"
set $variable1 [dict create]

# `dict set` takes a variable *name*
dict set $variable1 modifyPt $variable2

# `dict get` takes a variable *value*
dict get [set $variable1] modifyPt       ; # => 3.5400 7.3200

In a similar way, you can use arrays in the same awkward way:

array set $variable1 [list modifyPt $variable2]
parray $variable1                    ; # => PATH_xyz(modifyPt) = 3.5400 7.3200
puts [set ${variable1}(modifyPt)]    ; # => 3.5400 7.3200

or the truly horrible

puts [subst -nobackslashes -nocommands $${variable1}(modifyPt)]
2

I'm not sure I understand what you're after, but here are some examples of how to indirectly reference an array element in tcl:

% set array(key1) {value 1}
value 1
% set aname array
array
% set ${aname}(key2) {value 2}
value 2
% array get ${aname}
key {some value} key1 {value 1} key2 {value 2}

% set ${aname}(key2)
value 2
% set key key2
key2
% puts "<[set ${aname}($key)]>"
<value 2>

In your example, you can just use set instead of puts:

% set variable2 {3.5400 7.3200}
3.5400 7.3200
% set variable1 PATH_xyz
PATH_xyz
% set ${variable1}(modifyPt) $variable2
3.5400 7.3200
% set ${variable1}(modifyPt)
3.5400 7.3200

And just as above, you can use it in a [...] command substitution:

% puts "${variable1}\(modifyPt)={[set ${variable1}(modifyPt)]}"
PATH_xyz(modifyPt)={3.5400 7.3200}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .