2016-03-24 17 views
1

我已经看过Passing list to Tcl procedure,我无法正确理解如何正确执行它。 为了把它在上下文中,这是我如何通过名单:将一个列表传递给一个进程

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”传递它,但它返回一个错误。我的程序中的其他一切都是完美的(如果我从任何一个单独的程序中获取代码并将其自行运行),我似乎无法让它正确地通过列表。

回答

1

这里不要使用大括号:new_partition {$ptable} - 括号抑制变量扩展,并要传递的7个字符的字符串 $p 吨一个b 升Ë

参见规则#6 http://tcl.tk/man/tcl8.6/TclCmd/Tcl.htm

只是传递变量:new_partition $ptable

同理:

delete_partition $ptable 
print_partition $ptable 
write_partition $ptable $fn 

你已经证明实际上并没有修改您传递给它的参数的print_table过程,所以你并不真的需要返回一个值。 另外,如果你只是将它们传递给format,你并不需要将ptable的行分解为单个变量。你可以反过来说,PROC成

# 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 
+0

这似乎很好的手续3个工作,但它是有问题与写程序,因为我需要传递两个变量。它是相同的格式? – Peter

+0

我刚刚添加到我的答案 –

+1

@Peter是否有任何程序想要更新列表?如果是这样,还有一个不同的适用习惯用法。 –

相关问题