Wednesday, July 02, 2008

Tcl語法雜記

將一些我常用的Tcl語法記錄與此,以後好備查:

1.宣告變數:
set A 100

2.列印變數的值:
puts $A

3.Append變數:
set a {QA Engineer: }
set b {Lawrence Chiu}
puts $a
puts $b
append a $b
puts $a

4.Array:
#Set value to array
for {set i 5} {$i >= 0} {incr i -1} {
set myarray($i) $i
}
#Print array value
for {set i 0} {$i <= 5} {incr i +1} { puts "myarray($i)=$myarray($i)" }

5.將指令結果存於變數內:

set var [exec ifconfig]
puts $var
set var2 [exec ifconfig | grep "inet\ addr" | grep -v 127.0.0.1]
puts $var2

6.eval & subst:
set age 28
set str {I'm $age years old}
set cmd {puts "$str"}
eval $cmd
eval [subst $cmd]

7.foreach:
set SUM 0
foreach test {1 2 3 4 5} {
puts "$test"
set SUM [expr $SUM + $test]
}
puts "SUM=$SUM"

8.if:
set A 100
if {$A==101} {
puts "A=101"
} else { puts "A=100" }

9.開關檔:
set ls [exec ls]
set file [open file w]
puts $file $ls
close $file

10.positional應用:
set count [llength $argv]
puts $count
for { set i 0 } { $i <= [expr $count-1] } { incr i +1} { puts [lindex $argv $i] } 11.positional應用, foreach:
foreach a $argv {
puts $a
}

11.proc:
#functin f1
proc f1 {a b} {
return [expr $a + $b]
}

#Main program
set A 100
set B 150

set sum [f1 $A $B]
puts "A=$A"
puts "B=$B"
puts "A+B=$sum"

12. RE:
set var1 {abcde}
set var2 {b1234}
set var3 {aabcd}

puts "var1=$var1"
puts "var2=$var2"
puts "var3=$var3"
puts "\r"

puts "Which variable have a character?"
if {[regexp {a} $var1]} {
puts "var1 have a character"
} else { puts "var1 haven't a character" }

if {[regexp {a} $var2]} {
puts "var2 have a character"
} else { puts "var2 haven't a character" }

if {[regexp {a} $var3]} {
puts "var3 have a character"
} else { puts "var3 haven't a character" }
puts "\r"
puts "Which variable include number?"

if {[regexp {[0-9]} $var1]} {
puts "var1 have number"
} else { puts "var1 haven't a number" }

if {[regexp {[0-9]} $var2]} {
puts "var2 have number"
} else { puts "var2 haven't number" }

if {[regexp {[0-9]} $var3]} {
puts "var3 have number"
} else { puts "var3 haven't number" }

13.string:
set A "hello world!"
puts $A
puts [string length $A]
puts [string index $A 4]
puts [string range $A 6 9]
puts [string range $A 6 end]
puts [string toupper $A]
puts [string tolower $A]

14.switch:
set A yes
switch $A {
yes { puts "yes"}
no { puts "no" }
YES { puts "YES" }
default { puts "Not match!" }
}

15.while
set SUM 0
set i 1
while { $i <= 100} {
set SUM [expr $SUM + $i]
incr i 1
}
puts "SUM=$SUM"

Tcl online man page: http://www.tcl.tk/man/

2 comments:

TerryWang said...

帽客兄您好...小弟算是測試界的新手, 最近剛踏入測試...公司需要用到TCL來開發測試程式...上網做功課瀏覽到帽客兄您這裡...想問問帽客兄TCL該如何學習是否可以建議一下小弟, 小弟非資訊科系畢業, 走上IT產業純粹因為喜歡接觸...真的很想把這份別人認為不可能的測試工作做好...希望您能給小弟多點指導!! 感激不盡了!!

瘋狂帽客 said...

Hi Terry,
Tcl wiki: http://wiki.tcl.tk/

有很多豐富的資料可以參考,希望對你有幫助。
另外請記得多多使用google search你碰到的問題,很多時候都找的到答案,research skill對於我們這一行是很重要的工作技能,加油!