Search code examples
tclread-eval-print-loop

How to retrieve the last command's return value in TCL interpreter?


In Tcl, if I evaluate a command, and my expression failed to store the result in a variable, other than reevaluating the command, is there a way to retrieve the last command's return value in a TCL interpreter? For example, in some lisps, the variable * is bound to the result of the last evaluation, is there something like that in TCL?


Solution

  • The Tcl interpreter loop — which is pretty simple minded, with very few hidden features — doesn't save the last result value for you; it assumes that if you want to save that for later, you'll do so manually (or you'll repeat the command and get the result anew so you can save it then).

    If you want to save a value for later, use set. You can use * as the name of the variable (it is legal) but it's annoying in practice because the $var syntax shortcut doesn't work with it and instead you'd need to do:

    % set * [expr {2**2**2**2}]; # Or whatever...
    65536
    % puts "the value was ${*}... this time!"
    the value was 65536... this time!
    % puts "an alternative is to do [set *]"
    an alternative is to do 65536
    

    This will probably be a bit annoying when typing; use a name like it instead.

    % set it [expr {2**2**2**2}]; # Or whatever...
    65536
    % puts [string length [expr {123 << $it}]]
    19731
    

    (That last number has rather a lot of digits in it, more than I expected…)