定义变量在TCL中使用之前

时间:2013-03-02 06:14:06

标签: variables tcl

我是TCL的新手,我正试图将我的大脑包裹在它所使用的“”,{}和[]的所有用法中。我以前习惯用其他语言做的事情是在使用之前,在应用程序开始时定义我的变量。以下代码有效:

puts "Please enter an integer of choice to be added: "
flush stdout
gets stdin intAnswer

puts "Please enter a second integer of choice to be added: "
flush stdout
gets stdin intAnswerTwo

puts "Please enter a third integer of choice to be added: "
flush stdout
gets stdin intAnswerThree

puts "The total of the three integers is: [expr $intAnswer + $intAnswerTwo + $intAnswerThree]"

我想要做的是在使用之前定义变量。就这样:

set intAnswer 0
set intAnswerTwo 0
set intAnswerThree 0
set intTotal 0

此代码位于开头,不适用于其余代码。我错过了什么?

1 个答案:

答案 0 :(得分:1)

代码看起来对我来说绝对正常,但[expr {$intAnswer + $intAnswerTwo + $intAnswerThree}]会更好(因为它会停止对变量内容的潜在重新解释,这既是安全性又是性能问题)。

但是,如果您真的想要拥有用户的整数,则需要验证他们的输入。这很容易通过编写一个程序来完成工作,这样你就可以重复使用它(即,你重构代码来获取一个值,这样你就可以使用更复杂的版本并使其正确一旦):

proc getIntFromUser {message} {
    # Loop forever (until we [exit] or [return $response])
    while true {
        puts $message
        flush stdout
        set response [gets stdin]
        # Important to check for EOF...
        if {[eof stdin]} {
            exit
        }
        # The validator (-strict is needed for ugly historical reasons)
        if {[string is integer -strict $response]} {
            return $response
        }
        # Not an integer, so moan about it
        puts "\"$response\" is not an integer!"
    }
}

现在您已经拥有该程序,其余代码可以成为:

set intAnswer      [getIntFromUser "Please enter an integer of choice to be added: "]
set intAnswerTwo   [getIntFromUser "Please enter a second integer of choice to be added: "]
set intAnswerThree [getIntFromUser "Please enter a third integer of choice to be added: "]

puts "The total of the three integers is: [expr {$intAnswer + $intAnswerTwo + $intAnswerThree}]"

编写好的Tcl代码(或几乎任何其他语言的优秀代码)的艺术是知道重构有什么好处。一个很好的起点是“如果你做两次或更多,做一次并分享”。如果你能给这个程序一个好名字和清晰的界面,这是一个双重的好处,这清楚地表明你已经做对了。的确,你也可以选择:

set total [expr {
    [getIntFromUser "Please enter an integer of choice to be added: "] +
    [getIntFromUser "Please enter a second integer of choice to be added: "] +
    [getIntFromUser "Please enter a third integer of choice to be added: "]
}]

puts "The total of the three integers is: $total"

用户观察到的结果将是相同的。