带有可选参数的 TCL 过程调用

问题描述:

有一个 TCL 脚本,它在不同的命名空间中有多个具有相似名称 func 的过程定义.流程如下:

There is a TCL script which has multiple procedure definitions with similar name func in different namespaces. Procedures look like this:

proc func {a} {
    puts $a
}

所有那种过程只有一个参数 a .所有这些过程都是从整个脚本的一行中调用的:

All that kind of procedures have only one argument a . All that kind of procedures are called from one single line in whole script:

func $a

我需要在其他命名空间中创建另一个具有相似名称 func 的过程定义.但该过程将有两个参数.该过程也需要从与其他同名过程相同的行调用.过程如下:

I need to create another procedure definition also with similar name func in other namespace. But that procedure will have two parameters. That procedure is also need to be called from the same line that other procedures with same name. Procedure looks like this:

proc func {a b} {
    puts $a
    puts $b
}

我现在需要修改调用所有过程 func $a 的那一行,以便它可以调用所有带有一个参数的过程和带有两个参数的新过程.但是不能更改带有一个参数的过程定义.调用所有这些过程 func $a 的那一行应该是什么样的?

I need now to modify the line that calls all that procedures func $a so, that it can call all procedures with one parameter and new procedure which has two parameters. But procedures definitions with one parameter must not be changed. What line that calls all these procedures func $a should look like?

我从那个答案中找到了解决方案:https://*.com/a/22933188/1601703.我们可以得到过程接受的参数个数,并做出相应的 if 语句,将使用相应的过程调用:

I found the solution from that answer: https://*.com/a/22933188/1601703 . We can get the number of argument that procedure accepts and make coresponding if statments that will use corresponding procedure call:

set num [llength [info args func]]

    if {$num == 1} {
        func $a
    } elseif {$num == 2} {
        func $a $b
    }