2016-11-15 114 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]'會更好。 –

相關問題