Funky Tcl extensibility

Darren New wrote in comp.lang.tcl on 2002-01-16:

Something someone here said made me think of this. Talk about changing the syntax of a language...

 proc where {what} {
    set caller [info level -1]
    set body [info body $caller]
    set body [split $body \n]
    foreach line $body {
        if {-1 != [string first $what $line]} {
            # Or do more complicated processing
            puts $line
        }
    }
    return -code return
 }

 proc here {} {
    where zip
    zippidy doo dah
    zippidy ahy
    Oh my my what a wonderful day.
    zippy the pinhead says
    drink plenty of fluids
 }

 here

As where returns -code return (and thus terminates its caller as well), anything after it is not seen by the Tcl parser. Instead, where "eats" its caller's body and does with it what it pleases (putsing those lines that contain "zip", like a sort of grep)... Amazing food for thought. (RS) Here comes my variation (note that the set command is compiled early, so must still be according to Tcl rules):

 proc selfextract {what} {
    set caller [lindex [info level -1] 0]
    set res {}
    foreach line [lrange [split [info body $caller] \n] 2 end] {
        if {-1 != [string first $what $line]} {
            lappend res $line
        }
    }
    return -code return [join $res \n]
 }
 proc extract {{what zip}} {
    selfextract $what ;#--- rest is data-----
    zippidy doo dah
    zippidy ahy
    #set foo bar grill <- this would else still be detected!
    Oh my my what a wonderful day.
    zippy the pinhead says
    drink plenty of fluids
 }
 extract e

AK Note that in the code above the tcl bytecode compiler does not see that where stops the execution in the procedure. That means that anything behind the where still has to be in valid tcl syntax. It is not necessary that the commands are known, but the syntax (braces, brackets, etc.) has to be right.