Programmer
Programmer

Reputation: 8727

Pass variable in list and expect its literal value

I was trying to write a simple script where I create a list out of some existing variable and when I print the same expect its literal value:

set testString "John A. Smith, Mobile:001-445-4567-0987, Pin-556789"
set results  { address contact $testString }
puts $results

But I get the below output:

address contact $testString 

Where I was expecting - how can I achieve the same:

address contact John A. Smith, Mobile:001-445-4567-0987, Pin-556789 

Upvotes: 0

Views: 165

Answers (2)

Jerry
Jerry

Reputation: 71598

Braces prevent substitution of variables, so use double quotes instead:

set results " address contact $testString "
puts $results
#  address contact John A. Smith, Mobile:001-445-4567-0987, Pin-556789

Or use subst to force the substitution afterwards:

set results { address contact $testString }
set results [subst $results]
puts $results
#  address contact John A. Smith, Mobile:001-445-4567-0987, Pin-556789

Or if you actually mean to have a list where the first element is address, the second contact and the third being $testString's value, then you can use list, except the output will look different:

set results [list address contact $testString]
puts $results
# address contact {John A. Smith, Mobile:001-445-4567-0987, Pin-556789}

But that way, you can get testString back if you do something like lindex $results 2, whereas if you used any of the earlier methods, you would get only the first word of testString, that is, John.

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137787

When you do:

set results  { address contact $testString }

you are creating a literal string (without substitutions) and assigning it to a variable. This is what {…} does; it's just like 'single quotes' in Unix shells except for being nestable.

To get a substitution in there, you either use "double quotes", or to run the literal string through the subst command:

set results " address contact $testString "
set results [subst { address contact $testString }]

Upvotes: 0

Related Questions