It's a construct that can automatically clean up garbage after finishing a task.
For example, open is usually combined with a chan close. A "with" construct will automatically close the file descriptor (aka. handle).
Reasonably use the "with" construct can make your code visibly clearer.
proc getFinalByOp {op opret} { switch -exact -- $op { open { return [list chan close $opret] } default { return [list] } } } # # op: a command # opargs: @op's arguments # body: code that will be executed # ?_finally?: provide a 'finally' yourself # ?varname?: result of @op # proc with {op opargs body {_finally {}} {varname handle} } { set finally $_finally try { set [set varname] [$op {*}$opargs] if {$finally eq {}} { set finally [getFinalByOp $op [set [set varname]]] } eval $body } finally { eval $finally } }
This implementation only supports open, and it's buggy (see Discussions below).
with open {a.txt w} {chan puts $handle "hello world"} with open {a.txt r} {puts [read $fd]} {} fd with puts {"a test"} {set a {hello}} {puts $a} ;# a meaningless example
From the IRC channel,
<miguel> I am afraid that 'general with' will not work - not with bodies that try to use variables from the calling env <miguel> ... nor with commands that resolv differently in the calling env and in the proc's namespace