2
votes

What I want to do is parse an argument to a tcl proc as a string without any evaluation. For example if I had a trivial proc that just prints out it's arguments:

proc test { args } {
    puts "the args are $args"
}

What I'd like to do is call it with:

test [list [expr 1+1] [expr 2+2]]

And NOT have tcl evaluate the [list [expr 1+1] [expr 2+2]]. Or even if it evaluated it I'd still like to have the original command line. Thus with the trivial "test" proc above I'd like to be able to return:

the args are [list [expr 1+1] [expr 2+2]]

Is this possible in tcl 8.4?

2

2 Answers

3
votes

You cannot do this with Tcl 8.4 (and before); the language design makes this impossible. The fix is to pass in arguments unevaluated (and enclosed in braces). You can then print them however you like. To get their evaluated form, you need to do this inside your procedure:

set evaluated_x [uplevel 1 [list subst $unevaluated_x]]

That's more than a bit messy!


If you were using Tcl 8.5, you'd have another alternative:

set calling_code [dict get [info frame -1] cmd]

The info frame -1 gets a dictionary holding a description of the current command in the context that called the current procedure, and its cmd key is the actual command string prior to substitution rules being applied. That should be about what you want (though be aware that it includes the command name itself).

This is not available for 8.4, nor will it ever be backported. You might want to upgrade!

1
votes

When passing the arguments into test, enclose them in braces, e.g.: test {[list [expr 1+1] [expr 2+2]]}