Tcl脚本语言简单语法介绍

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 }


以上程序运行截图如下:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值