2016-11-15 112 views
1

我想将Tcl键列表传递给一个函数,当我访问函数中的变量时,其类型不是键列表。用于获取密钥列表的软件包是TclX。将TCL键列表作为参数传递给函数会改变其类型

示例代码:

keylset x port1.port "1/1" 
keylset x port1.stream "1" 
# keylkeys x works at this point 

keylset y port1.port "1/1" 
keylset y port2.port "1/2" 
keylset y port1.stream "1" 
# keylkeys y works at this point 

# Following call returns error: the error is keyed list entry must be a valid, 2 element list, got "port1" 
proc_name $x 

# Following call is successful 
proc_name $y 

# procedure is part of a package and the package is sourced at the start of the script 
proc proc_name {x} { 
    # puts x for one port input -> port1 {{port 1/1} {stream 1}} 
    # puts y for one port input -> { {port1 {{port 1/1} {stream 1}}} {port2 {port 1/1}} } 
    puts [keylkeys x] 
} 

我不知道为什么密钥列表无法识别传递到过程

+0

'keylset'不是Tcl的标准部分。你应该包括什么扩展名提供该命令作为你的问题的一部分。假设它们不仅仅是代码中定义的过程。 – patthoyts

+0

我正在使用TclX,编辑了包含信息的问题。 – Aditya

回答

0

时,我没有与tclx来测试一个TCL,但 大概 需要通过列表变量名称到proc然后用upvar里面。试试这个:

keylset x ... 
keylset y ... 

proc_name x  ;# just the varname 
proc_name y  ;# just the varname 

proc proc_name {varname} { 
    upvar 1 $varname keyedlist 
    puts [keylkeys keyedlist] 
} 
+0

您的解决方案适用于提供的示例,但未在实际脚本中使用。在脚本中,该过程是脚本开始处的包的一部分,您认为这可能会产生影响吗?我添加了解决问题的答案 – Aditya

+0

是的,我的答案取决于您能够将'upvar'命令添加到proc中。如果它超出了你的控制范围,那么你必须将键控列表视为一个普通列表。 –

0

这是解决我的问题是别人在未来同样的问题(要归功于我真棒的一个同事):

由于程序内部的打印显示,一组{}缺失,我在函数调用之前添加了一组额外的""

# please refer to the code in the question section, I am just adding the changed snippet here 
proc_name \"$x\" ;# solved the problem inside the procedure 
+1

'proc_name [list $ x]'会更好。 –

相关问题