Using Variables in Associative Arrays

I ran into this problem when I tried to insert a variable into the value part of an associative array(or hash) in Tcl. Apparently, in this situation the variable substitution does not take place...

#The Variable
set ship "Enterprise"

#Make the array
array set star_trek {
	location	"Bridge of the $ship"
	problem		"Power surge"
	solution	"a fuse"
}

puts $star_trek(location) ;# Prints "Bridge of the $ship"

I think the '{' and '}' around the code prevents the substitution. Yeah, those brackets are very confusing in Tcl. You can get around this error with this code...

#The Variable
set ship "Enterprise"

#Make the array
set star_trek(location)	"Bridge of the $ship"
set star_trek(problem)	"Power surge"
set star_trek(solution)	"a fuse"

puts $star_trek(location) ;# Prints "Bridge of the Enterprise"

Comments

Anonymous at 21 Aug, 2007 03:12
'{' and '}' indeed prevent substitution. However, try instead

array set star_trek [list \
location "Bridge of the $ship" \
problem "Power surge" \
solution "a fuse" \
]

and everything works fine
Reply to this.
Comment


Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed