1

In Ruby or Perl one can assign more than variable by using parentheses. For example (in Ruby):

(i,j) = [1,2]
(k,m) = foo() #foo returns a two element array

Can one accomplish the same in TCL, in elegant way? I mean I know that you can do:

foreach varname { i j } val { 1 2 } { set $varname $val }
foreach varname { k m } val [ foo ] { set $varname $val }

But I was hoping for something shorter/ with less braces.

1 Answer 1

7

Since Tcl 8.5, you can do

lassign {1 2} i j
lassign [foo] k m

Note the somewhat unintuitive left-to-right order of value sources -> variables. It's not a unique design choice: e.g. scan and regexp use the same convention. I'm one of those who find it a little less readable, but once one has gotten used to it it's not really a problem.

If one really needs a Ruby-like syntax, it can easily be arranged:

proc mset {vars vals} {
    uplevel 1 [list lassign $vals {*}$vars]
}

mset {i j} {1 2}
mset {k m} [foo]

Before Tcl 8.5 you can use

foreach { i j } { 1 2 } break
foreach { k m } [ foo ] break

which at least has fewer braces than in your example.

Documentation: break, foreach, lassign, list, proc, uplevel

Sign up to request clarification or add additional context in comments.

1 Comment

The order of variables is because that's what the old TclX extension used to do in its lassign implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.