Tcl Programming CyberDaemons
Tango Training
1
Agenda •Tcl簡介 •變數和運算 •列(List)的操作 •陣列和陣列操作 •物件
Tango Training
2
TCL語言 • Tcl 是“工具控制語言(Tool Control Language)" 的縮寫。Tk是 Tcl“圖形工具箱"的擴展(Extension) ,它提供各種標準的 GUI 介面項。Tcl 是一個高階的 電腦語言,語法類似 shell script 與 C 語言之間。 而 tk 是一個使用者界面發展工具,有buttons、 menus、listboxes、 scrollbars 等等。 • Tcl是屬於直譯式的程式語言,就像早期的 Basic 一 樣,所以在寫好 Tcl Script 後需要一個 Tcl 直譯程 式執行您的 Tcl Script 。 而 Tcl 的直譯器叫做 tclsh。 • Tcl 是以可擴展(Extension)性、短的學習曲線和易於 嵌入為特定目標而設計的。
Tango Training
3
Tcl 歷史 •John K. Ousterhout於 1988 年開始開發 Tcl/Tk,有好的代碼可重用性,又要簡單易學。 •Tk 的開發始於 1989 年,第一個版本於 1991 年問世。提供一個互動式介面 。 •Tk usable around 1992 •see http://www.tcl.tk/doc/tclHistory.html
Tango Training
4
Tcl 特點 • high-level scripting language
• most platforms – Unix, Mac, Windows – hides UI, system call differences
– less code than Motif or Win32
• interpreted
• autoloading
– execute directly, without compiling or linking
• extensible
– automatically load libraries
• free
– commands in Tcl or C
– source – no royalties
• embeddable – Tcl interpreter callable from C Tango Training
5
Tcl結構
Tango Training
6
如何使用tcl •方式一:tclsh的互動模式 $ tclsh % set x 7 7
•方式二:wish的視窗模式 $ wish % button .b –text “Hello” –command exit % pack .b
Tango Training
7
如何使用tcl •方式三:C語言的程式開發 #include main(int argc, char *argv[]) { Tcl_interp *interp = Tcl_CreateInterp(); code = Tcl_EvalFile(interp, argv[1]); if (*interp->result != 0) { printf(“%s\n”, interp->result); } } Tango Training
8
簡單的TCL程式 •hello.tcl: set s "Hello World" puts $s –Command: $tclsh hello.tcl –Result: 也可以先進入tclsh (直接下tclsh命令) Hello World
再一行一行鍵入程式 or 下 “tcl 檔名” 命今也可以
Tango Training
9
Tcl 語法 •Everything is a list of words – no fixed grammar –first word is command
•{} delay evaluation, may nest •"" only needed when spaces: – set x "foo" = set x foo
•everything can be done dynamically: new procedures, variables, name spaces, ... •interpreter model, but internally compiled into bytecode Tango Training
10
變數(variable)的宣告 •利用set來指定變數值。 –Ex.: set a 101
•unset取消此變數 –Ex.: unset a
Tango Training
11
變數替換(variable substituion) • 變數替換 – variable substitution: set a 17 – command substitution, evaluated as separate script: set b [expr $a*4] – backslash substitution: set x \$a
• 範例
指令
結果
set b 18 set a [expr $b+2] set a "b-3 is [expr $b-3]"
18 20 b-3 is 15
Tango Training
12
變數功能 • incr increments variable •append adds strings to end: append msg "more text" • argv variable is list of command line arguments • env is list of environment variables
Tango Training
13
表示式(Math expressions) • 最常使用的是expr • 語法: – expr arg ?arg arg ...?
• 範例: if {$x == $y} { ...} set x [expr {$x + 7}] set y [expr {log($y)}]
Tango Training
[]代表一個 完整指令
14
表示式練習 指令 set b 5 expr ($b*4) - 3 expr $b <= 2 expr $a * cos(2*$b) expr {$b * [fac 4]}
結果 5 17 0 -5.03443 120
Tango Training
15
incr指令 • 語法: – incr varName ?increment?
• 作用: – 作加法運算 – Ex.: set i 0 incr i incr i 4 – Result: 0 1 5
Tango Training
16
append指令 • 語法: – append varName ?value value value ...?
• 作用: – 在變數後面附加資料 – Ex.: set i 1 append i 2 3 4 5 – Result: 12345
Tango Training
17
exec指令 •語法: –exec ?switches? arg ?arg ...?
•作用: –執行外部程式 –Ex.: exec umane –Result: Linux
Tango Training
18
字串 „Tcl 對於字串有更多的處理能力 指令 結果 set a Bill Bill expr {$a < "Anne"} 0 expr {$a < "Mary"} 1
„<, >, <=, >=, ==, and != work on strings „Beware when strings can look like numbers
Tango Training
19
字串處理 •字串處理的相關指令 regexp regsub
format split scan join
string
„string subcommands compare match trimleft
first last index length range toupper tolower trim trimright
„Note: all indexes start with 0. end means last char
Tango Training
20
練習時間 把講義的前面內容,在主機上練習一 遍
Tango Training
21
Tcl串列(Tcl lists) • list = ordered collection of elements • separated by spaces or tabs • any proper list can also be a Tcl command! • concat list list – concatenate lists concat {a b c} {d e f} a b c d e f
• join list sep – convert to string with separator join {a b c} ", " a, b, c • lappend var element element – append to end of list
Tango Training
22
Tcl list manipulation • lindex list index lindex {a b c} 1 b
• linsert list index value value linsert {a b c} 0 A {B C} A {B C} a b c
• list value value list {a b c} {d e} f {a b c} {d e} f • llength list llength {a b c} 3 • lrange list first last lrange {a b c} 1 end b c
Tango Training
23
Tcl lists manipulation • lreplace list first list value ... • lsearch ?-glob|-regexp? list pattern • lsort ?-command c? –increasing|decreasing list
lsort –decreasing {a b c} c b a
Tango Training
24
list指令 •語法: –list ?arg arg ...?
•作用: –建立清單 –Ex.: list a b " c d" –Result: a b { c d}
Tango Training
25
eval指令 •語法: –eval arg ?arg ...?
•作用: –將參數當成script, 用遞迴方式執行 –Ex.: eval [list set i] 3 –Result: 3
Tango Training
26
lindex指令 • 語法: – lindex $list ?index...?
• 作用: – 在list中抽出索引指定的資料 – Ex.: lindex {a b c d e} 2 lindex {a b c d e} end – Result: c e
Tango Training
27
linsert指令 • 語法: – linsert $list index element ?element element ...?
• 作用: – 在指定的位置插入資料 – Ex.: set aa [list a b c d e f] linsert $aa end-3 1 2 3 – Result: a b c 1 2 3 d e f
Tango Training
28
lappend指令 • 語法: – lappend varName ?value value value ...?
• 作用: – 在變數值後將引數當list附加資料 – Ex.: set var a lappend var b c d – Result: a b c d
Tango Training
29
concat指令 •語法: –concat ?arg arg ...?
•作用: –將多個list合併 –Ex.: set a [concat "a b" 1 2 {c {d e}}] lindex $a 5 –Result: d e
Tango Training
30
llength指令 •語法: –llength $list
•作用: –計算出list元素的個數 –Ex.: llength {a b} –Result: 2
Tango Training
31
lrange指令 •語法: –lrange $list first last
•作用: –在list中將索引範圍內的元素列出 –Ex.: lrange {a b c d} 1 end –Result: b c d
Tango Training
32
練習時間 上機操作 30 分鐘
Tango Training
33
Tcl陣列(Tcl Arrays) •語法: –array option arrayname ?arg1 arg2 …?
•設定陣列的元素: set myarray(00) 365 puts $myarray(00) –Result: 365
Tango Training
34
option: set指令 •語法: –array set arrayname $list
•作用: 一定要偶 –設定陣列元素 數個才行 –Ex.: array set myarray {0 123 00 456 a b} –Result: 0 123 00 456 a b
Tango Training
35
option: get指令 • 語法: – array get arrayname index
• 作用: – 回傳一組含陣列索引和值的陣列元素。 – Ex.: array set myarray {0 123 00 456 a b} array get myarray a array get myarray – Result: a b 0 123 00 456 a b
Tango Training
36
option: exists指令 •語法: –array exists arrayname
•作用: –若此array存在,則回傳1,否則為0。 –Ex.: array set myarray {0 123 00 456 a b} array exists myarray –Result: 1
Tango Training
37
option: names指令 • 語法: – array names arrayname
• 作法: – 回傳陣列索引名稱清單 – Ex.: array set myarray {0 123 00 456 a b} array names myarray – Result: 0 00 a
Tango Training
38
option: size指令 •語法: –array size arrayname
•作用: •回傳陣列大小 –Ex.: array set myarray {0 123 00 456 a b} array size myarray –Result: 3
Tango Training
39
option: unset指令 • 語法: – array unset arrayname ?pattern?
• 作用: – 將符合pattern的索引拿掉。 – Ex.: array set myarray {0 123 00 456 a b} array unset myarray 0 array name myarray – Result: 00 a
Tango Training
40
休息時間 下一階段要介紹流程控制
Tango Training
41
TCL之流程控制 •If-else •Switch •For loop •Foreach loop •While loop
Tango Training
42
if-then-else •命令的語法為: if expression ?then? body1 ?else? ?body2?
if expr1 ?then? body1 ?elseif? expr2 ?then? body2…..?elseif? exprN ?else? bodyN
Tango Training
43
流程控制範例(if-else) 一定要空一格 其它也一定要
• Ex.:
set grade 90 if {$grade >= 90} { puts "Your level is A!" } elseif {$grade < 90} { puts "Your level isn’t A!" } else { puts "You set wrong data!" }
• Result: Your level is A!
Tango Training
44
switch •語法: switch ?option? string pattern body ?pattern body…. switch ?option? string {pattern body ?pattern body…}
Tango Training
45
流程控制範例(switch) •Ex.: set num 1 switch $num { 1 {puts "I’m 2 {puts "I’m 3 {puts "I’m default {puts }
David."} Terry."} Ruby."} "What’s your name?"}
•Result: I’m David.
Tango Training
46
While Loop •語法: while booleanExpr body
Tango Training
47
流程控制範例(while loop) •計算1+2+…+100 –Ex.: set a 0 set ans 0 while {$a < 101} { set ans [expr $ans+$a] incr a 1 } puts $ans –Result: 5050 Tango Training
48
Foreach loop •語法: foreach loopVar valueList commandBody
Tango Training
49
流程控制範例(foreach loop) •計算1+2+…+10 –Ex.: Set j 0 foreach i {1 2 3 4 5 6 7 8 9 10} { set j [expr $i+$j] } puts $j –Result: 55
Tango Training
50
For loop •語法: for initial test final body
Tango Training
51
流程控制範例(for loop) •計算1+2+…+100 –Ex.: set ans 0 for {set a 0} {$a < 101} {incr a 1} { set ans [expr $ans+$a] } puts $ans –Result: 5050
Tango Training
52
練習時間 各種流程控制的方式都要上機操作!
Tango Training
53
Tcl程序(Tcl procedures) •基本語法為: proc 程序名稱 {參數1 參數2…} { 主體Body }
•Procedures behave just like built-in commands: –sub1 3
=> 2
•Arguments can have default values: proc decr {x {y 1}} { expr $x-$y } Tango Training
54
程序範例 • procedures can be created dynamically proc power {base p} { set result 1 while {$p > 0} { set result [expr $result * $base] set p [expr $p-1] } return $result }
• 執行 power 2 6
Tango Training
55
正規表達式Regular expressions •Tcl提供了兩個用於正規表達式的命令regexp 和regsub。 •這裡的正規表達式實際上是擴展的正規表達式, 與egrep相一致。 •支持^$.+?\>\<()|[]
Tango Training
56
Regexp命令 • 語法 regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
•範例:計算數字 regexp -all {[0-7]} "I like 7-Up"
=>returns 1 •範例:檢查字串 regexp T(cl|k) "I mention Tk" w t => returns 1 (match), w becomes "Tk", t gets "k" Tango Training
57
正規表達式 . (period) ^ $ \x [chars] (regexp) * + ? |
matches any character matches start of a string matches end of a string single character escape matches any of chars. ^: not. -: range. matches the regexp matches 0 or more of the preceding matches 1 or more of the preceding matches 0 or 1 of the preceding can be used to divide alternatives. Tango Training
58
例外處理 •catch用於阻止由於錯誤而導致中斷執行。 •執行catch,每次都返回TCL_OK,無論是否有錯 誤發生。 如有錯誤發生返回1,反之返回0 。 „Can intercept errors (like exception handling): catch {expr {2 +}} msg 1 (catch returns 0=OK, 1=err, other values...) puts msg syntax error in expression "2 +"....
Tango Training
59
檔案處理(File I/O) „Tcl file I/O commands: open close fblocked eof
gets seek flush read tell cd fileevent puts pwd filename
glob fconfigure source
„File commands use 'tokens' to refer to files set f [open "myfile.txt" "r"] => file1 (按實際情況會有不同) puts $f "Write this text into file" close $f Tango Training
60
檔案處理 „gets and puts are line oriented set x [gets $f] reads one line of $f into x „範例 set f [open /etc/passwd r] => file2 (按實際情況會有不同) gets $f => root:x:0:0:root:/root:/bin/bash
Tango Training
61
檔案處理 „read can read specific numbers of bytes read $f 100 => (up to 100 bytes of file $f) „seek, tell, and read can do random-access I/O set f [open "database" "r"] seek $f 1024 read $f 100 => (bytes 1024-1123 of file $f)
Tango Training
62
info指令 „what variables are there? –info vars, info globals, info locals, info exists
„what procedures have I defined, and how? –info procs, info args, info default, info body, info commands
•範例 proc ff {abc} {puts Hello} info args ff =>abc
Tango Training
63
練習時間
Tango Training
64