您的位置:首页 > 其它

Tcl脚本语言简单语法介绍

2013-12-16 18:45 423 查看
set a "puts hi"

eval $a

set value [expr 0==1]

puts $value

set value2 [expr 2+3]

puts $value2

puts "I am [expr 10*2] years old, and my I.Q. is [expr 100-25]"

set my_planet "venus"

if {$my_planet == "earth"} {

     puts "I feel right at home."

} elseif {$my_planet == "venus"} {   ;#elseif不能换行书写 特别注意

xie

     puts "This is not my home."

} else {

     puts "I am neither from Earth, nor from Venus."

}

#switch

set num_legs 4

switch $num_legs {

2 { puts "It could be a human." }

4 { puts "It could be a cow." }

6 { puts "It could be an ant." }

default { puts "It could be anything." }

}

# for

for {set i 0} {$i < 5} {incr i 1 } {

 puts "In the for loop, and i == $i"

}

#while

set i 0

while {$i < 5} {

   puts "In the while loop, and i == $i"

   incr i 1

}

#foreach

foreach vowel {a e i o u} {

   puts "$vowel is a vowel"

}

#process

proc sum_proc {a b} {

    return [expr $a +$b]

}

proc magnitude { num } {

    if { $num > 0 } {

       return $num

}

   set num [ expr $num*(-1)]

   return $num

}

set num1 12

set num2 14

set sum [ sum_proc $num1 $num2]

puts "The sum is $sum"

puts "The magnitude of 3 is [ magnitude 3 ]"

puts "The magnitude of -2 is [ magnitude -2]"

#process2

proc dumb_proc {} {

set myvar 4

puts "The value of the local variable is $myvar"

global myglobalvar

puts "The value of the global variable is $myglobalvar"

}

set myglobalvar 80

dumb_proc

#array

set myarray(0) "zero"

set myarray(1) "one"

set myarray(2) "two" 

for {set i 0 } { $i < 3 } { incr i 1 } {

puts "$myarray($i)"

}

#array1

set person_info(name) "Tom"

set person_info(age) "24"

set person_info(occupation) "Plumber"

foreach thing { name age occupation } {  ;#don't write name,age,occupation

puts "$thing == $person_info($thing)"

}

#array3

set person_info(name) "Tom"

set person_info(age) "24"

set person_info(occupation) "Plumber"

foreach thing [ array names person_info ] {

puts "$thing == $person_info($thing)"

}

#file output

set f [open "/home/myfile" "w"]

puts $f "We live in Beijing."

puts $f "234"

close $f

#eval

set infile [open "/home/ns2131216/file.txt" "r"]

while { [gets $infile Op] >= 0} {

  set Operation "expr $Op"

  set Result [eval $Operation]

  puts stdout "$Op = $Result\n"

}

#upvar

proc decr {n m} {

upvar $n upa

set upa [expr $upa - $m]

}

set nb 12

decr nb 3

puts $nb

#uplevel

proc ff {} {

set a xiaolevel

}

set a globallevel

ff

puts $a

#uplevel1

proc ff {} {

uplevel set a xiaolevel

}

set a globallevel

ff 

puts $a

#error and catch

proc div {a b} {

if { $b == 0 } {

   error "divided by zero"

} else {

   return [expr $a / $b]

}

}

div 8 3

div 8 0

catch { div 8 3 }
catch { div 8 0 }

以上程序运行截图如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Tcl 脚本语言