tcl Uplevel set command fails when value has multiple words

271 Views Asked by At

All, What i am trying to do: Proc A calls Proc B, Using uplevel command from B i am trying to set variable in proc A scope. Error occurs when the value has spaces.

proc B { } {
    set string1 "Test"
    set string2 "Test with space"
    uplevel 1 set key1 $string1
    uplevel 1 set key2 $string2
    return 0
}

proc A { } {
    set res [B]
    puts "key1 is $key1"
    puts "key2 is $key2"
}

If i comment out key2, it works fine. When add key2, it fails with following error.

wrong # args: should be "set varName ?newValue?"
    while executing
"set key2 Test with space"

Any suggestions on how to overcome this error. Appreciate your help.

1

There are 1 best solutions below

1
Bryan Oakley On

uplevel 1 set key2 $string2 becomes set key1 test with space, which is why you are getting your error.

The best practice is to build up the command you want to run using [list]:

uplevel 1 [list set key2 $string2]

This will guarantee a well-formed set statement.