本文介绍了如何编写具有默认值和选项的 tcl 过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个执行以下操作的 tcl 程序 -

I am trying to write a tcl procedure which does the following -

proc myProc {arg1 def1} {arg2 def2} {
...
...
}

tcl> myProc -arg1 val1 -arg2 val2
arg1 variable has val1
arg2 variable has val2

tcl> myProc -arg1 val1
arg1 variable has val1
arg2 variable has def2

tcl> myProc -?
myProc -arg1 <value1> -arg2 <value2>
arg1 - required argument [default value is 10]
arg2 - optional argument [default value is 20]
help - print this message
?    - print this message

这在 tcl 中可行吗?

Is this possible in tcl?

我查了一些被问到的问题,我看到的是这个 问题.这部分满足了我的要求,但我找不到任何可以帮助我解决问题的方法.请指导我!

I looked up some of the questions that have been asked and what I see is this question. This does partially what I require but I couldn't find anything that would help me solve my problem. Please guide me!

推荐答案

阅读 proc 手册页仔细:参数列表必须是单个列表.你在考虑这个:

Read the proc man page carefully: the list of arguments has to be a single list. You were thinking about this:

% proc myproc {{a 42} {b 54}} { puts "a=$a b=$b" }
% myproc
a=42 b=54
% myproc 1
a=1 b=54
% myproc 1 2
a=1 b=2

请注意,第一个参数被分配给 a -- 您不能为 b 提供值并使用 a 的默认值与这种方法.

Note that the first argument is assigned to a -- you cannot provide a value for b and use the default value for a with this method.

要使用类似命令行的选项,最简单的方法是:

To use command-line-like options, the simplest way is this:

% proc myproc {args} {
    array set data [list -a 42 -b 54 {*}$args]
    puts "a=$data(-a) b=$data(-b)"
}
% myproc
a=42 b=54
% myproc -a 1
a=1 b=54
% myproc -b 2
a=42 b=2
% myproc -b 2 -a 3
a=3 b=2
% myproc -c 4
a=42 b=54

这个方法的一个问题是你必须传递偶数个参数,否则array set会抛出错误:

One problem with this method is that you must pass an even number of arguments, or array set will throw an error:

% myproc 12
list must have an even number of elements

这篇关于如何编写具有默认值和选项的 tcl 过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 14:36
查看更多