2012-03-09 97 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

相关问题