TCL array key is not being recognized [duplicate]
Possible Duplicate:
tcl array question - key with quotes
I have the following code:
set my_list1 {"a" "b"}
set my_list2 {"@1" "@2"}
array set my_array {}
foreach li1 $my_list1 li2 $my_list2 {
set my_array($li1) $li2
}
puts $my_array("a")
On the list line I get ERROR "can't read my_array("a"): no s开发者_StackOverflow中文版uch element in array"
Why?
I have it, because when I write
set newVar "a"
puts $my_array($newVar)
it returns the value!
This is just one of those things in Tcl. The array element is not my_array("a")
-- it's my_array(a)
. Don't include the quotes when referencing the array. They're actually not necessary, although in that case note harmful, when you're installing the data into the array in the first place -- i.e.,
set my_list1 {a b}
would be just fine.
Tcl looks enough like a "normal" programming language that it's easy to forget how primitive its parser really is. Remember that everything is broken down into "words" by whitespace. If a double-quote character isn't preceded by whitespace, it isn't at the start of a word, and it no longer has any special significance. A reference to an array element is a single word, and after variable interpolation, it has to have exactly the right text. You can't put quote marks around the element name because simply those quote marks are not part of the correct text of that word.
精彩评论