將一些我常用的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 0set 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/