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.
Anonymous at 19 Jan, 2009 12:42
Another workaround for the above mentioned issue is:-

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"
Reply to this.
saravanan at 28 Jan, 2009 04:11
Another workaround for the above mentioned issue is:-

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 Enterprise"
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




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