user2895478
user2895478

Reputation: 383

Tcl String Manipulation and Substitution

set i 0
set student$i tom

(of course, this is equivalent to set student0 tom)

I want to get the value of student0, that is, string "tom". How can I get it if I have to use $i to represent 0 here? I tried $(student$i) or $"student$i" and many other ways, but I cannot get string "tom". (I don't want to hard code it like $student0) in here.

Is there any way to solve this? Thanks!

Upvotes: 1

Views: 314

Answers (2)

fahad
fahad

Reputation: 3179

1] set i 0

set student$i "tom"

puts [subst $[subst student[subst $i]]]

2] Using Array

set i 0

set student($i) "tom"

puts $student($i)

Upvotes: 1

Bryan Oakley
Bryan Oakley

Reputation: 385890

You can use the set command -- it returns the value of the variable:

puts "the student is [set student$i]"

However, this sort of thing is generally more trouble than it's worth. Use an array, with i as an index into the array:

set student($i) tom
puts "the student is $student($i)"

Upvotes: 6

Related Questions