我是Tcl的新手,所以我正在学习基础知识。我编写了一个函数来计算数组的总和并打印其元素。这是代码
proc print_sum { tab } {
set s 0
foreach key [array names tab] {
puts "${key}=$tab($key)"
incr $s $tab($key)
}
puts "the sum = $s"
}
这是我的称呼方式:
print_sum tab
我创建了这样的标签:
set tab("1") 41
set tab("m2") 5
set tab("3") 3
set tab("tp") 9
set tab("2") 7
set tab("100") 16
但是输出错误!它输出0而不是实际总和,并且不输出任何元素。但是当我直接使用代码而不将其编写为函数时,它就可以工作。
答案 0 :(得分:0)
问题在于您要将字符串“ tab”传递给proc,然后将其存储在变量名“ tab”中。这只是一个普通变量,而不是数组,因此当您执行array names tab
时,您会得到一个空列表。 foreach循环循环零次,总和仍为零。
您需要使用upvar
命令链接到调用者的堆栈框架中的“ tab”数组:
proc print_sum { arrayName } {
upvar 1 $arrayName a ;# "alias" the array in the caller's scope
set s 0
foreach key [array names a] {
puts "${key}=$a($key)"
incr s $a($key) ;# increment the *variable* not the *variablevalue*
}
puts "the sum = $s"
}
print_sum tab
输出
"tp"=9
"100"=16
"1"=41
"2"=7
"3"=3
"m2"=5
the sum = 81