Here's a simple bit of code to extend any ensemble-like command by means of tcl8.5's namespace ensemble command. CMcC 6Mar2006
Larry Smith: stacking does a similar job.
package provide extend 1.0 package require Tcl 8.5 # extend a command with a new subcommand proc extend {cmd body} { if {![namespace exists ${cmd}]} { set wrapper [string map [list %C $cmd %B $body] { namespace eval %C {} rename %C %C::%C namespace eval %C { proc _unknown {junk subc args} { return [list %C::%C $subc] } namespace ensemble create -unknown %C::_unknown } }] } append wrapper [string map [list %C $cmd %B $body] { namespace eval %C { %B namespace export -clear * } }] uplevel 1 $wrapper }
Here's the file command extended with newer and newerthan subcommands:
extend file { proc newer {a b} { return [expr {[file mtime $a] > [file mtime $b]}] } proc newerthan {mtime path} { return [expr {[file exists $path] && ([file mtime $path] > $mtime)}] } }
Here's the dict command extended with the modify subcommand:
# extra useful dict commands extend dict { proc modify {var args} { upvar 1 $var dvar foreach {name val} $args { dict set dvar $name $val } } }
LV So, this seems like a nice bit of functionality. Would it be useful enough to include either in Tcl itself or at least Tcllib?
quick hacks ?
AMG: See also my [dict getnull] example in [dict get].
In a comp.lang.tcl posting dated Fri, 04 Apr 2014 09:25:30 DKF posted this code in answer to a question about how to extend the string command ensemble:
"A cheaper way to extend string would be to do:"
namespace eval ::string { proc _unknown {ens cmd args} { set map [namespace ensemble configure $ens -map] dict set map $cmd ::string::$cmd namespace ensemble configure $ens -map $map return [list ::string::$cmd] } proc pos {str pos} { return [string range $str $pos $pos] } } namespace ensemble configure ::string -unknown ::string::_unknown