Michael
Michael

Reputation: 9058

How to unpack a list into variables in Tcl?

In Python I can write something like:

my_list = [4, 7, "test"]
a, b, c = my_list

After that a is 4, b is 7 and c is "test" because of the unpack operation in the last line. Can I do something like the last line in Tcl? To make it more clear, I want something like that:

set my_list {4 7 test}
setfromlist $mylist a b c

(I.e. setfromlist would be the command I'm looking for.)

Upvotes: 6

Views: 5619

Answers (1)

RHSeeger
RHSeeger

Reputation: 16262

You want lassign:

% lassign
wrong # args: should be "lassign list ?varName ...?"
% lassign {1 2 3} a b c
% set a
1
% set b
2
% set c
3

If you're using an older version of Tcl (that doesn't have lassign), you can use foreach to achieve the same result

foreach {a b c} {1 2 3} {break}

Upvotes: 15

Related Questions