3 ms·
proc with {file as name block} { uplevel 1 [list set $name $file] uplevel 1 [list eval $block] uplevel 1 [list close $file] } with [open foo.
by sebcat 11y ago
proc with {file as name block} {
uplevel 1 [list set $name $file]
uplevel 1 [list eval $block]
uplevel 1 [list close $file]
}
with [open foo.txt w] as file {
puts $file "Hello, World!"
}
I'm sure it's possible to do it in a cleaner way without [set], but my Tcl is a bit rusty.
- a8da6b0c91d 11y agoStill leaks on an exception. That's also an annoying construct to be forced to use.
- nilkn 11y agoYou could easily wrap the middle uplevel in a catch block to handle exceptions, and this sort of "with" construct is pretty common in a lot of very popular languages today. While it would be nice if this were baked into the language, it's pretty astonishing how extensible Tcl is without even having to touch the realm of C extensions.
- srean 11y agoI think this precisely one of Tcl's strengths. Few other languages apart from Lisp and Tcl lets you write your own control flow syntax from within the language (and at runtime).
- sigzero 11y agoI like the "with". Python has that construct. It's not annoying and easy to remember.