我已经看过将列表传递给Tcl过程,但我不太明白如何正确地执行它。放在上下文中,这就是我传递列表的方式:
switch $choice {
n {
set ptable [new_partition {$ptable}]
}
d {
set ptable [delete_partition {$ptable}]
}
p {
set ptable [print_table {$ptable}]
}
w {
set ptable [write_table {$ptable $fn}]
puts "Saving file...nExiting..."
break
}
q {
puts "Exiting..."
break
}
default {
puts "Illegal option"
}
}
这是程序之一的示例
proc print_table {ptable} {
# Set format string
set formatStr {%-16s%-8s%-8s%-8s%-8s%-8s}
# Print the contents of ptable to stdout
puts [format $formatStr "nPartition" "Start" "End" "Blocks" "ID" "System"]
puts "--------------------------------------------------------"
foreach item $ptable {
set parts [lindex $item 0]
set sCyl [lindex $item 1]
set eCyl [lindex $item 2]
set blok [lindex $item 3]
set id [lindex $item 4]
set sys [lindex $item 5]
puts [format $formatStr $parts $sCyl $eCyl $blok $id $sys]
}
return $ptable
}
Ptable的创建是正确的,但一旦我将其传递给其中一个过程,它就会丢失所有信息。我试着用"{*}$ptable"传递它,但它返回了一个错误。我的程序中的其他一切都运行得很好(如果我从任何一个过程中提取代码并将其单独放置,它就会全部工作),我只是似乎无法让它正确地通过列表。
此处不要使用大括号:new_partition {$ptable}
--大括号禁止变量扩展,并且您正在传递7个字符的字符串
请参阅中的规则#6http://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm
只需传递变量:new_partition $ptable
类似:
delete_partition $ptable
print_partition $ptable
write_partition $ptable $fn
您所展示的print_table
过程实际上并没有修改您传递给它的参数,因此您实际上不需要返回值。此外,如果您只是将ptable的行传递给format
,则不需要将它们分解为单独的变量。你可以把这个过程变成
# Print the contents of ptable to stdout
proc print_table {ptable} {
set formatStr {%-16s%-8s%-8s%-8s%-8s%-8s}
puts [format $formatStr "nPartition" Start End Blocks ID System]
puts "--------------------------------------------------------"
foreach item $ptable {
puts [format $formatStr {*}$item]
}
}
不要这样做
set ptable [print_table $ptable]
但是做这个
print_table $ptable