Version 1 of Playing with with

Updated 2013-09-14 18:29:39 by ekd123

What's "with"

It's a construct that can automatically clean up garbage after finishing a task.

For example, open is usually combined with a chan close.

One possible implementation

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.

How to use it

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