0

私は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

先頭に配置されたこのコードは、残りのコードでは機能しません。私は何が欠けていますか?

4

1 に答える 1

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 コード (またはほとんどすべての他の言語の優れたコード) を作成する技術は、リファクタリングの優れた点を知ることです。良い出発点は、「2 回以上行う場合は、1 回行って共有する」ことです。手順に適切な名前と明確なインターフェイスを付けて、手順が正しいことを明確に示すことができれば、二重のメリットがあります。実際、次のこともできます。

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"

ユーザーが観察する結果は同じです。

于 2013-03-02T13:07:32.240 に答える