Version 2 of using

Updated 2006-08-26 21:20:58

NEM 26 Aug 2006: C# has a nice little construct for automatically closing a resource once you are finished with it. Here's a Tcl version of this using command:

 proc using {varName chan script} {
     upvar 1 $varName var
     set var $chan
     set rc [catch { uplevel 1 $script } result]
     catch { close $chan }
     return -code $rc $result
 }

Which you can then use like:

 using fd [open somefile.txt] { puts [read $fd] }

or

 foreach host $hosts {
     using sock [socket $host $port] { ... do stuff on $host ... }
 }

RS I'm not so happy with the name using: it means other things in other languages (like with packages or namespaces) and does not indicate that it's for channels. Something like LISP's WITH-OPEN-FILE might be clearer to understand :)

KPV Actually the C# construct is quite useful and not just for files but for many types of objects which grab some scarce resource. (Technically, it works with any object which implements the IDispose interface).


[ Category Control Structure | Category File | Category Networking ]