tcl基本語法與指令 - 歡迎蒞臨南華大學cmwu/lab/tcl.doc · web...
TRANSCRIPT
TCL
TCL Tutorial
Original written by Rick In 2003
Revision by maa In 2004/6
TCL .........3
TCL .....4
......9
String ......9
List ....17
Array ..............20
...22
If Then Else...........................23
Switch.......................................24
While.....................................26
For........................................27
Foreach........................................28
Break Continue............................29
Catch........................................29
Procedure......30
TCL .....32
TCL
TCLTool Command LanguageTickleScripting Language(Interpreter)TCL
1.
2. TCL UNIXShell languagesBourne Shell (sh)C Shell (csh)Korn Shell (ksh) PerlTCL (variableflow controlprocedure) (Process)
3. (embed) TCL
TCL
(UNIXWindowsMacintosh ) TCL
(Regular Expressions) (pattern)
C TCL Extension Library TCL Tk extension TCL GUI Programming expect extension
package(ftp, httpemail, dns, msn, icq ) (TK, BWidget, Tktable, SpecTCL, VisualTCL, ActiveState KOMODO) (incrTcl, XOTcl, SNIT ) (MetaKit, daFT )
TCL TCL Package TCL Script (TCL ) TCL Script
TCL
TCL Script TCL (TCL command) TCL
command arg1 arg2 arg3 .
TCL
() (grouping) TCL (substitution) TCL () TCL
TCL Script
# Demo1.tcl
puts stdout one; puts stdout two
set x 4
set y 6
puts "$x + $y = [expr $x + $y]"
puts {$x + $y = [expr $x + $y]}
puts "Hello\n\nTCL!"
% ./Demo1.tcl
one
two
4 + 6 = 10
$x + $y = [expr $x + $y]
Hello
TCL!
TCL
(substitution symbols)
$
$ set x puts x Console
set x 5
puts stdout $x
$
[ ]
TCL Demo1.tcl L5
puts "$x + $y = [expr $x + $y]"
x y TCL expr exprTCL x y expr expr
(grouping symbols)
TCL
{ }
TCL Demo1.tcl L6
puts {$x + $y = [expr $x + $y]}
TCL $x + $y = [expr $x + $y]TCL
puts {$x + $y =
[expr $x + $y ]
}
\
C base \n TCL (VB )
TCL
#
# # TCL
puts hello ;# here is comment
# TCL # puts
TCL TCL set
set x 5
set y 6
set PI 3.14
set PI*2 6.28 ;# PI*2
puts $PI*2
set PI
TCL set set PI ( $ )
unset
unset x y PI
info exists incr info exists
if {![info exists counter]} {
set counter 0
} else {
incr counter ;# counter 1
}
TCL info global
% info global
argv argv0 tcl_version tcl_interactive var auto_oldpath errorCode auto_path errorInfo unknown_handlers unknown_handler_order auto_index env tcl_patchLevel argc tcl_libPath _ tcl_platform tcl_library
argc argv0 TCL Script argv listenv tcl_version TCL
(Substitution and Grouping)
TCL
TCL
TCL
TCL
$ TCL
TCL
TCL
if {$x > 1}{puts $x}
^ if
TCL
- ~ !
(Unary minus) / NOT(Bit-wise not) / NOT(Logical not)(string)NOT
* / %
(Multiply) / (divide) / (remainder) (string)
+ -
(Add)(subtract)
>
(Shift Left / Right)
< > =
(less)/(greater)/(less than or equal)/(greater than or equal)10
== !=
(equal)/(not equal)0/1
&
AND(Bit-wise and)
^
XOR(Bit-wise exclusive or)
|
OR(Bit-wise or)
&&
AND(Logical and)10
||
OR(Logical or)01
x ? y : z
x y z
TCL
string
list
array
handle I/O channelsocket, thread
String
TCL stringappendformatscan binarystring
% set name Brent Welch
% string length $name
=>11
string string string
% string rick
bad option "rick": must be bytelength, compare, equal, first, index, is, last, length, map, match, range, repeat, replace, tolower, toupper, totitle, trim, trimleft, trimright, wordend, or wordstart
string
string bytelength str
(UTF-8 encoding)string length
string compare ? -nocase? ?-length len?str1 str2
01
-nocase
% string compare nocase Rick rick
=>0
-length
string compare length 3 rick ricp
=>0
string equal ?-nocase? str1 str2
str1str210
string first subString string
startIndex
string -1startIndex
% string first rick ilovericktoo
=>5
string index string charIndex
indexindex0endend-N
% string index rick 2
=>c
% string index rick end
=>k
% string index rick end-2
=>i
string last string
string -1startIndex
% string frist rick rickANDrick
=>0
% string last rick rickANDrick
=>7
string length string
string map ?-nocase? charMap string
charMap
% string map {i c} rick
=>rcck
% string map {ri ja} rick
=>jack
% string map {r j i a} rick
=>jack
string match ?-nocase? pattern str
pattern10 glob style pattern match
?
*
[ ][abc] abc [a-z]
\?
% string match tcl* tcltk
=>1
% string match tcl* rick
=>0
?
% string match ric? rick
=>1
% string match ri?? rick
=>1
% string match ric? rickpeng
=>0
[ ]
% string match {[a-z]} rick
=>0
% string match {[a-z][a-z][a-z][a-z]} rick
=>1
string range str i j
strij end
% set x [string range iloverick 2 5]
=>over
string repeat str count
strcount
% string repeat rick 3
=>rickrickrick
string replace str first last ?newstr?
newstrFirstlastnewstrnewstr
% string replace iloverick 1 4 hate
ihaterick
string tolower string ?first? ?last?
% string tolower ILOVERICK 1 4
=>IloveRICK
string totitle string ?first? ?last?
% string totitle iloverick 1 4
=>iLoverick
string toupper string ?first? ?last?
% string toupper iloverick 1 4
iLOVErick
string trim string ?chars?
charschars
% string trim ililoverick rick
lilove
% string trim kkkloverickkkkk rick
=>love
string trimleft string ?chars?
string charschars
% string trimleft iloverick i
=>loverick
% string trimleft kkkloverickkkk lk
=>overickkkk
string trimright string ?chars?
string charschars
% string trimright iloverick rick
=>ilove
string wordend str index
str
% string wordend {I love rick} 5
=>6
string wordstart str index
str
% string wordstart iloverick 9
=>0
string
string compare string equal
if {[string compare $s1 $s2] == 0} {
# s1 and s2 are equal
}
if {[string equal $s1 $s2]} {
# s1 and s2 are equal
}
== ack TCL 160xa10 string compare string equal
if { 0xa == 10} { puts ack }
append
append
% set foo rick
rick
% append foo i love you
rickiloveyou
format
Cprintfformat
format spec value1 value2
spec
(position specifier)
(flags)
(field width)
(precision)
(word length)
(conversion character)
(Grouping)
d
(Signed integer)
u
(Unsigned interger)
i
hex(0x)octal(0)
o
(Unsigned octal)
x or X
(Unsigned hexadecimal)x
c
ASCII
s
f
a.b
e or E
a.bE+-c
g or G
%f%e
i$i1 format
% format {%2$s} one two three
=>two
TCL $ $ i$ (grouping) $
% format %2\$s one two there
=>two
-
+
space
0
0
#
octal0Hex0x
scan
Cscanfscan
scan string format ?varName? ?varName?
% scan a 123 Rick char num str
% puts char = $char num = $num str = $str
=> char = 97 num = 123 str =rick
scan format %c ASCII
Binary
binary format template value ?value .?
Binary scan value template variable ?variable ?
binary template manual page
c (template) 97 ASCII
% binary format c 97
=>a
c (template) 6 ASCII var1
% set input 6
% binary scan $input c var1
% set var1
=> 54
scan list
% binary scan abcde c3 list
% set list
=> 97 98 99
% lindex list 1 ;# list 1
=> 98
scan
% binary scan abcde ccc x y z
% puts x = $x y = $y z = $z
% x = 97 y = 98 z = 99
List
TCL list list, lindex, llength, lrange, lappend, linsert, lreplace,
lsearch, lset, lsort, concat, join, and split list list list list foreach list
list TCL array list
list arg1 arg2..
list list
% list rick test
=>rick test
set list
% set mylist {rick test}
=>rick test
lindex list i
listi index list
% set x {r i c k}
=>r i c k
% lindex $x 2
=>c
llength list
list
% set x {r i c k}
=>r i c k
% llength $x
=>4
lrange list i j
listij
% set list {t p t s 1}
=>t p t s 1
% set y [lrange $list 1 2]
=>p t
lappend listVar arg arg..
listVar
% set list rick
=>rick
% lappend list iloveyou
=>rick iloveyou
Linsert list index arg arg..
i
% set list {i love rick}
=>i love rick
% linsert $list 1 really
=>i really love rick
lreplace list i j arg arg
list i j lreplace list
% set list {i love rick}
=>i love rick
% set list2 [lreplace $list 1 1 hate]
=>i hate rick
lsearch ?options? list pattern
pattern -1 Glob
% set list {i love rick}
=>i love rick
% lsearch $list love
=>1
lset listVar index
?index? value
value list i
% set list {i love rick}
=>i love rick
% lset list 1 hate
=>i hate rick
lsort ?switches? list
switch list -ascii, -dictionary, -integer, -real, -increasing, -decreasing, -index ix, -unique, -command command.
% set list [list maa cxlin ognoc]
% lsort $list
=>cxlin maa ognoc
concat list list
list
% set list1 [list 1 maa]
% set list2 [list 2 cxlin]
% set list3 [list 3 ognoc]
% set listAll [concat list1 list2 list3]
% llength $listAll
=>6
join list ?joinString?
list joinString
% set list [list i love rick]
% join $list
=>i love rick
% join $list ###
=>i###love###rick
split string
?splitchars?
list splitChars
% set list [split a b c]
% length $list
=>3
% set list [split a#b#c #]
=>a b c
% lrange $list 0 end
=>a b c
list foreach foreach(array names index)
% foreach index [array names env] {
% puts $index = $env(index)
% }
=>OS = Windows NT
=>windir = C:\Windows
=>ComSpec = C:\WINDOWS\system32\cmd.exe
=>()
foreach list join
proc join {list sep{} } {
set s {} ;# s is the current separator
set result {}
foreach x $list {
append result $s $x
set s $sep
}
return $result
}
Array
TCL array Perl associative array TCL set
% set price(apple) 10
% set price(orange) 12
% set quantity(apple) 5
% set discount(apple) 0.8
puts $price(apple)
=>10
array exists arr
arr 1
% set price(apple) 10
% array exists price
=>1
array get arr
?pattern?
arr list (Pattern)
% set price(apple) 10
% set price(orange) 12
% array get price
=>orange 12 apple 10
array names arr
?mode? ?pattern?
arr list mode ( exact-glob(default) regexp)
% array names price
=>orange apple
array set arr list
list
% array set price [list apple 10 orange 12]
% array get price
=>orange 12 apple 10
array size arr
arr
% array size price
=>2
array unset arr
?pattern?
% array set price [list apple 10 orange 12]
% array get price
=>orange 12 apple 10
% array unset price app*
% array get price
=>orange 12
% set price(apple) 10
% array get price
=>orange 12 apple 10
% array unset price
% set price
=>can't read "price": no such variable
array startsearch arr
(token id)
array nextelement arr id
token-id
array anymore arr id
token-id10
array donesearch arr id
id
array statistics arr
arr(hash table)
foreach
% set price(apple) 10
% set price(orange) 12
% array get price
=>orange 12 apple 10
% foreach {key value} [array get price] {
price($key) = $value
}
=>price(orange) = 12
=>price(apple) = 10
% foreach key [array names price] {
price($key) = $price($key)
}
array get foreach TCL list array (iterate)
% set searchToken [array startsearch price]
% while {[array anymore price $searchToken]} {
set key [array nextelement price $searchToken]
set value $price($key)
puts $key = $value
}
array donesearch price $searchToken
=>orange = 12
=>apple = 10
TCLTCL(Statement)whileforforeachifswitchcatchbreakcontinuereturnerrorTCL
(command body)
set x 2
set y 3
if {$x < $y} {
puts x is less than y!
}
TCL() if if (command body)ififTCL Script
ififTCLif
If Then Else
If
if expression ?then? body1 ?else? ?body2?
if (expression) (body1) (body2)
if {$x > 0} {
puts x is greater than zero!
} else {
puts x is less than zero!
}
thenelsethenifelseif
if {$temperature < 24} {
puts Its cool!
} elseif {$temperature < 30} {
puts Its a little hot!
} else {
puts Its quite hot!
}
switch
Switch
switch (pattern matching)switch
switch flags value pattern1 body1 pattern2 body2 ?default defaultBody?
switchdefaultdefault
switchflags
-exact value
-globglob style string matchglob style switch
-regexp (Regular Expression)
--switchflag (value) -- value - valueflag
switch
set x 5
set y 5
switch -glob -- $x \
$y { puts x = y } \
{[0-9]} { puts x = 5 } \
default { puts x > 10 }
switch -glob -- $x {
$y { puts x = y }
[0-9] { puts x = 5 }
default { puts x > 10 }
}
x = y
x = 5
TCL (substitution)switchTCL () $y 5TCL[0-9]switchxyx = y
switchswitch $y x$yTCL [0-9] x5 [0-9] x = 5
set var see
switch -glob -- $var {
{see} -
{saw} -
{seen} { puts All mean the same thing!}
}
=>All mean the same thing
While
while booleanExpr body
while while autoexec.bat Consolegets -1
set fileId [open c:/autoexec.bat r]
while {[gets $fileId line] >= 0} {
puts stdout $line
}
close $fileId
whileTCL TCLwhile $i 0whilewhile
set i 0 ; while $i06/22/04 22:04:11
=>06/22/04 22:04:12
clock secondsclock format {%D %T} %m/%d/%y %H:%M:%Safter (millisecond)
whilefor (forinitialfinal)
set fileId [open c:/autoexec.bat r]
for {} {[gets $fileId line] >=0} {} {
puts stdout $line
}
close $fileId
for (iterate)listlist
for {set i 0} { $i < [llength $list] } {incr i} {
puts [lindex $list $i]
}
forlistforllengthlindexlistforeach
Foreach
foreach listVar list body
foreachlist (iterate)
set total 0
set numList [list 1 2 3 4 5 6 7 8 9 10]
foreach num $numList {
set total [expr $total + $num]
}
puts stdout total = $total
=>total = 55
foreachlist
foreach {key value} {apple 10 orange 12} {
puts $key=$value
}
=>apple=10
=>orange=12
array getlistforeach
set price(apple) 10
set price(orange) 12
foreach {key value} [array get price] {
puts $key=$value
}
=>orange=12
=>apple=10
break continue
breakcontinuebreakcontinue (iteration)
Catch
catch command ?resultVar?
TCLopenTCLTCL Scriptcatchcatchcatchcatch00
catchTCL
if {[catch {open c:/autoexec.bat r} fileId ]} {
puts opening file error: $fildId
} else {
while {[gets $fileId line]} {
puts $line
}
close $fileId
}
Procedure
TCL procedureTCLTCL procprocedure
proc procName argList body
procprocedureprocedureprocedureprocedurereturnTCL
procedure
set PI [expr 2 * asin(1.0)]
proc c_area {rad} {
global PI
return [expr $PI * $rad $rad]
}
% c_area 3
=> 28.2743338823
PIradprocedureexprTCLasinPIc_area (Scope) global
(default value)c_arearad1
set PI [expr 2 * asin(1.0)]
proc c_area { {rad 1} } {
global PI
return [expr $PI * $rad $rad]
}
% c_area 3
=> 28.2743338823
% c_area
=> 3.14159265359
args (TCL listargs)
proc printArgs { args } {
puts Total arguments: [llength $args]
puts The argument list = [lrange $args 0 end]
}
% printArgs
=>Total arguments: 0
=>The arguments list are:
% printArgs one two three
=>Total arguments: 3
=>The arguments list are: one two three
TCLrenameTCLunknownoriginalUnknown
rename unknown originalUnknown
unknownunknownoriginalUnknownunknownunknownrenameexecexec
rename exec {}
TCL
TCL
after
append
array
binary
break
catch
cd
clock
close
I/O (stream)
concat
listlist
console
(Console)
continue
(iteration)
error
eof
eval
TCL ScriptTCL
exec
expr
fblocked
I/O channel
fconfigure
I/O channel
fcopy
I/O channel I/O channel
file
fileevent
I/O callback
flush
I/O buffer
for
foreach
format
C printf
gets
I/O
glob
(pattern)
global
procedure global procedure
history
if
incr
info
TCL
interp
TCL interpreter
join
list
lappend
list
lindex
list
linsert
list
list
listlist
llength
list
load
TCL shared library
lrange
list
lreplace
list
lsearch
(pattern)
lsort
list
namespace
namespace
open
package
package
pid
process id
proc
TCL procedure
puts
I/O
pwd
read
I/O
regexp
(Regular Expressions)
regsub
rename
TCL
return
procedure
scan
seek
I/O
set
socket
TCP/IP
source
TCL Script
split
list
string
subst
()
switch
tell
I/O
time
TCL
trace
unknown
TCL
unset
variable
namespace
vwait
TCL(event-loop)
while
3 34