Version 12 of Many ways to eval

Updated 2011-12-18 21:00:36 by RLE

Tcl commands are evaluated if the command name is the first word, at the beginning of a line or when bracketed. eval evaluates its arguments in some special ways (concateneates to a string, if not a pure list). Here are some apocryph alternatives:

Andreas Leitgeb pointed out on the comp.lang.tcl newsgroup (2002-08-07) that

 if 1 $cmd

is clearly faster then

 eval $cmd

MS explained: "Well: eval does not bytecompile the script as it is "usually" used for one-time scripts ... For more fast-and-surprising ways to do it, try one of

     interp eval {} $x
     namespace eval :: $x

as they both will compile the script."


Tcl chatroom, 2002-12-18:

suchenwi Another wrinkle is that eval does not byte-compile - for that you may use [if 1], [interp eval {}] or [namespace eval ::] ...

EE HOW many different eval commands are there?

dgp YM: [namespace eval [namespace current]]]

suchenwi But such things are not documented features and may change between releases, so don't bet on it. - How many? The four above, and there's also [uplevel 0] ... Don: yes - just quoting MS's hint, assuming that :: is current.

EE eek.

suchenwi Another way:

 foreach don't care {#body executed once, but may be left with break}

..which you could sugar as:

 interp alias {} breakable {} foreach _ _ ...

EE ok, there should be a wiki page about how many different ways there are to eval a command. (With discussions of relative merit, of course, and obfuscatory value if you like it that way...)

suchenwi BTW: change the above to:

 foreach don't {} {#and the body is not executed, like if 0 }

EE yes, I like that. [breakable] looks good.

suchenwi Well I'm not sure whether these really deserve propaganda - it's rather against KISS and all that...

EE really? that doesn't execute the body with don't set to {} ?

suchenwi No - foreach is not executed if the data list is all empty.

miguel foreach eval wayto {gimme $1}


Another special way is a one-off proc if you want to drop local variables immediately:

 proc _ {} {#body goes here, may upvar to see the outer world}; _; rename _ {}

DGP The comments here are straying off topic. There are indeed many synonyms for [eval] among Tcl's built-in commands, but the last several examples are not among them.