my_question
my_question

Reputation: 3245

How to define a variable with argument expansion

The following command runs as expected:

lappend {*}{arr 1}
puts [lindex $arr 0]

Now I am trying to make a variable of "{*}{arr 1}" like this:

set X "{*}{arr 1}"
lappend $X

But this does not work, seems $X is taken as one whole value, argument expansion is not effective.

So is it a requirement that argument expansion can not be through variable?

Upvotes: 0

Views: 114

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137787

The {*} is a syntactic feature of Tcl (from Tcl 8.5 onwards) just as [], "" or $ is. You have to write it in the script in order for it to count as argument expansion; otherwise it's just a sequence of three characters.

If you want something like

set X "{*}{arr 1}"
lappend $X

to work, you need to pass it through eval:

set X "{*}{arr 1}"
eval lappend $X

Note that this then means that X actually contains a script fragment; this can have all sort of “interesting” consequences. Try this for size:

set X "{*}{arr 1};puts hiya"
eval lappend $X

Use of eval in modern Tcl is usually a sign that you're going about stuff the wrong way; the key use in old scripts was for doing things similar to that which we'd use {*} for now.

Upvotes: 3

Jerry
Jerry

Reputation: 71598

No, within double quotes, { and } actually lose their meaning, so will {*}. Notice that puts "{}" and puts {} are different.

The closest I can think of to do what you're trying to do would be to use something like this:

set X {arr 1}
lappend {*}$X

So if you now execute puts [lindex $arr 0], you get 1 as output.

Upvotes: 1

Related Questions