2012-03-09 95 views
3
proc test {a b c } { 
     puts $a 
     puts $b 
     puts $c 
} 
set test_dict [dict create a 2 b 3 c 4 d 5] 

現在我要字典進入測試是這樣的:如何將帶有更多參數的字典傳遞給tcl中的proc?

test $test_dict 

如何使test只選擇在字典三個要素,其參數(鍵)相同的名稱。預期結果應該是:

2 
3 
4 

因爲它選擇在字典a b c但不d。我怎樣才能做到這一點?我看到一些代碼是這樣的,但我無法使它工作。

回答

5

我認爲你應該使用dict get

proc test {test_dic} { 
    puts [dict get $test_dic a] 
    puts [dict get $test_dic b] 
    puts [dict get $test_dic c] 
} 

set test_dict [dict create a 2 b 3 c 4 d 5] 
test $test_dict 

編輯: 另一個變化是使用dict with

proc test {test_dic} { 
    dict with test_dic { 
    puts $a 
    puts $b 
    puts $c 
    } 
} 

set test_dict [dict create a 2 b 3 c 4 d 5] 
test $test_dict 

但還是test得到一個列表。

+0

我看到參數列表包含單個元素,而不是列表,但在調用時,只有一個字典被傳入函數。我認爲作者在傳入參數列表時使用了一些技巧來擴展字典。 – Amumu 2012-03-09 05:43:29

+0

+1代表'dict with' – 2012-03-09 13:51:40

+0

或'dict with test_dict {test $ a $ b $ c}'(但是會污染調用者)。 – 2012-03-09 15:51:07

相關問題