版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)
文檔簡介
Tcl語言:本由本人獨立完成,唯一參考來源為 是在BSD 的原作者DavidN.WeltonClifFlyntTcl語言...................................................................................................................................... (1: (2: 3: 循環(huán)101-while循 添加新令到Tcl—— 19的的list命令- 25正則表達(dá)式例 26陷阱-正則表達(dá)式 27關(guān)聯(lián)數(shù) 文件 39命令構(gòu)造-format 43調(diào)試- 計時.................................................................................................................................. TimeandDate- 48通道I/O- 49子解釋 前歡迎來到Tcl。我們寫這本目標(biāo)是為了幫助你學(xué)習(xí)Tcl這門語言。它作為Tcl手冊頁面的副品,而它們提供了所有Tcl命令的一個參考。while”會顯示while命令的使用手冊頁。Comp.lang.tcl組。通過閱讀器或者GroupsNeilArjenDavid當(dāng)我們已經(jīng)安裝了Tcl,你接下來要調(diào)用使用的程序是tclsh。舉例來說,如 o.tcl文件,并且你想要執(zhí)行它,你可以這樣做:tclsho.tcl。根據(jù)你安裝的Tcl的版本及你使用的操作系統(tǒng)版本,tclsh程序可能只是一個真正的執(zhí)行體的,在微軟Windows下面,它可能到Tclsh是一個簡單令行交互式解釋器。你可以要么在命令行用啟動Tcl的方法如果輸入命令而沒有參數(shù)大部分的Tcl令會產(chǎn)生一個有用的錯誤TclshTcl解釋器方法之一,另一個常用的執(zhí)行體,已經(jīng)被安裝到了你的系統(tǒng)里,是wish,或者WIndowingS。這個版本的Tcl自動加載創(chuàng)建圖形用戶界面(GUI)的Tk擴展。本不涉及Tk,因此這里我們不使用wishtclsh提JeffHobbs編寫的TkCon強化版解釋器。EclipseIDEDLTKTclTcl用WikiTclIDETcl源代碼編輯器的。但是,不要慌。如果你不知道如何使用一個復(fù)雜的開發(fā)環(huán)境,通過簡單文本編輯器來寫Tcl代碼也是非常容易的。簡單文本輸傳統(tǒng)的本的起始點是經(jīng)典的“ 字符串,你就可以隨意使用Tcl,無論是自娛自樂還是為了掙錢。習(xí)他們之間的一些不同。記住,在Tcl里面,單引號并沒有它在其他編程語言如C,Perl,Python里面那樣重要。號或大括號括起來,Tcl解釋器會認(rèn)為其中的每個單詞都是一個分隔的參數(shù),并puts命令。puts命令會盡量把這些單詞評估為可選的參數(shù)。Tcl命令是由換行符或分號結(jié)束的一組單詞。Tcl注釋符是“”,它位于the#Thisisacommentatbeginningofalineputs{ o,World-InBraces}puts{Badcommentsyntaxexample}#*Error*-thereisnoputs"Thisisline1";puts"thisislineo,World;-Withasemicoloninsidethe#Wordsdon'tneedtobequotedunlesstheycontainwhite 變量賦Tcl里面,任何東西都可以用字符串表示,盡管它可能被表示成list,setsetfruit存空間。setset以兩個參以被包括,每一個數(shù)據(jù)可以通過數(shù)組下標(biāo)來。數(shù)組下標(biāo),在Tcl里面通過在下面是set命令的概要:setvarNamevarName有varName(index)如果你看一下示例代碼,你會注意到,set命令的第一個參數(shù)只是輸入了它的名字,而puts語句的第一個參數(shù)卻前綴了“$”符號。常用值傳遞參數(shù),而確實改變數(shù)據(jù)的值令通常用名稱傳遞數(shù)據(jù)。示例setsetX"Thisisastring"setY1.24puts$Xputsputs setlabel"ThevalueinYis:"puts"$label$Y"求值和置換(1:用””給參數(shù)分階段才是對合成令的求值。注意,只有一次置換操作被執(zhí)行。因此,在命令里面,自身變量的內(nèi)容會置換$varName,然后命令才執(zhí)行。假設(shè)我們設(shè)置Command-Math101”一節(jié)做更詳細(xì)解釋里面,varName當(dāng)前的內(nèi)容置換了$varName,然后整個字符串被打印到輸出設(shè)HexAudibleBell(鈴聲FormFeedclearscreen清NewLine(換行Tab(制表VerticalTab(垂直制表OctalValue(八進制disadigitfrom0- Hisahexdigit0-9,A-F,a-Thisrepresentsa16- HexUnicodecharacter.(16Unicode字符 HexValue(16進制值
Notethatthe\xsubstitution"keepsgoing"aslongasithashexdigits,andonlyusesthelasttwo,meaningthat\xaaand\xaaaaareequal,and\xaaAndanywaywill"eat"theAof"And".Usingthe\unotationisprobablyabetteridea.示例setZsetZ_LABEL"TheCapitolofNewYorkis:puts"$Z_LABEL$Z";#Printsthevalueofputs"$Z_LABEL\$Z";#Printsaliteral$ZinsteadofthevalueofZputs"\nBenFranklinisonthe\$100.00bill"seta100.00puts"Washingtonisnotonthe$abill" ;#Thisisnotwhatyouwantputs"Lincolnisnotonthe$$abill" ;#ThisisOKputs"Hamiltonisnotonthe\$abill" ;#Thisisnotwhatyouwantputs"BenFranklinisonthe\$$abill";#But,thisisputs"\n.................examplesofescapestrings"puts"Tab\tTab\tTab"puts"Thisstringprintsout\nontwolines"puts"Thisstringcomesout\onasingle求值和置換(2:用{}給參數(shù)分(”會被Tcl解釋器區(qū)別對待。在上一節(jié),你明白,引號隔的詞組許置換發(fā)在雙引號反,使用一對花括號不允許置換?;ɡㄌ柕淖址敛桓淖兊刂苯颖粋鬟f給命令。號號被處理。這依然是一個續(xù)行符(一行代碼擴展為兩行或多行。。如果字符串已經(jīng)分組了,或者引號,或者花括號,并且花括號例如,”foo{bar”串,號。示例setsetZsetZ_LABEL"TheCapitolofNewYorkis:\"andputs"$Z_LABEL$Z"http://TheCapitolofNewYorkis:Albanyputs{$Z_LABEL$Z}//$Z_LABEL$Zputs"\n.......examplesofdifferencesinnesting\{\"puts"$Z_LABEL{$Z}"http://TheCapitolofNewYorkis:{Albany}puts{Whosaid,"Whatthiscountryneedsisagood$0.05cigar!"?}//Whosaid,"Whatthiscountryneedsisagoodputs"\n.................examplesofescapestrings"puts{Therearenosubstitutionsdonewithinbraces\n\rputs{But,theescapednewlineat ofa\stringisstillevaluatedasaspace}//一行輸出,即續(xù)行符求值和置換(3:用[]給參數(shù)分把命令放到方括號()里面,你就可以得到該命令的結(jié)果。它功能上等價于sh編程里面的反單引號(,或者C語言里面的函數(shù)返回值。解釋器掃描整個命令,注意到,有一個命令置換要執(zhí)行:readsensor setsetxputs"Asimplesubstitution:sety[setxputs"Rememberthatsetreturnsthenewvalueofthevariable:X:$xY:$y\n"http://X:defY:defsetzsetx"Thisisastringwithinquoteswithinbraces"]}puts"Notethecurlybraces$z\n"http://[setxThisisastringwithinquoteswithinbraces"],大括號的關(guān)系seta"[setx{Thisisastringwithinbraceswithinquotes}]"http://Thisisastringwithinbraceswithinquotesputs"Seehowthesetisexecuted:$a"puts"\$xis:setb"\[sety{Thisisastringwithinbraceswithinquotes}]"http://[sety{Thisisastringwithinbraceswithin#Notethe\escapesthebracket,andmustbedoubledtobea#literalcharacterindoubleputsputs"Notetheescapesthebracket:\n\$bis$b"http://這里puts"\$yis:命令返回值-MathTclexprexprexpr手冊exprif,while和for循環(huán),這些將在稍后部分討論。這里給出的所有的expr的建議對這些其他”2+2”不是正常令)來評估,并返回結(jié)果值。Tcl表達(dá)式允許的運算符包括所有的expr{$i*10},而不要簡單地用expr$i*10。產(chǎn)生可能的安全缺口。expr命令執(zhí)行自己的對變量和命令的置換循環(huán),所以你應(yīng)該使用括號來防Tcl解釋器做這些(導(dǎo)致雙置換)。為了考慮%setuserinput{[putsDANGER!]}[putsDANGER!]%expr$userinput==10%expr{$userinput==1}號了這種潛在的。作為一個基本規(guī)則,要總是用括號包括表達(dá)式,無論expr還是一些其他接受表達(dá)式作為參數(shù)令(ifwhile)。操作數(shù)Tcl表達(dá)式由操作數(shù),操作符,和圓括號組合而成。空格也可以被使用階段,0x32ASCII碼“2expr50.數(shù)。浮點型數(shù)可以以遵循ANSIC編譯器接受的指定。例如,下面的全其上應(yīng)用有限集合的操作數(shù)八進制數(shù)700=7*8*8=448(十進制。%%exprexpectedintegerbutgot"0900"(lookslikeinvalidoctal操作數(shù)可以以下面指定: ~* +<<<><=eqnein0(false%expr{"9"==1%expr{"9"eq0&^|AND01僅對數(shù)值型有效(整數(shù),浮點數(shù).是z。x必須是數(shù)字值。%setx%expr{$x>0?($x+1):($x-1)}數(shù)學(xué)函數(shù)%%setx%setw%expr{[stringlength$w]-2*$x}類型轉(zhuǎn)換double()int()把一個數(shù)轉(zhuǎn)換成通常的十進制整數(shù)數(shù)(截斷小數(shù)部分wide()把一個數(shù)轉(zhuǎn)換成所謂的寬整數(shù)(這些數(shù)有更大的范圍entire把一個數(shù)轉(zhuǎn)換成一個空間大小適當(dāng)?shù)恼麛?shù),而不需要進行截斷。這可能和int()和wide()返回相同,或者是任意大小的一個整數(shù)。setsetXsetYsetZ[expr{$Y+setZ_LABEL"$Yplus$Xisputs"$Z_LABEL$Z"http://256plus100isputs"Thesquarerootof$Yis[expr{sqrt($Y)puts"Becauseoftheprecedencerules\"5+-3*4\"is:[expr{-3*4+5}]"http://-7putsputs"Becauseofthe[expr{(5+-3)*\"(5+-3)*4\"setAsetB##Thetrigonometricfunctionsworkwithradians...setpi6[expr##Workingwitharraysputs"Sum:[expr7b2計算機和數(shù)#Compute1#Compute1milliontimes1%puts[expr#Compute1milliontimes1%puts[expr{1000000*1000000.}] 數(shù)的一個子集。他們處理從-231to231-1(一般說來,即-2147483648to2147483647的整數(shù)。數(shù)又位于另一組和彎路的中心。浮點數(shù)有更大的范圍,他們可以用來處理像1.2和4.1415026這樣的數(shù)。浮點數(shù)典型的范圍大體上是-1.0e+3001.0e-300,0.0,1.0e-300到0.000…1(…代表295個0)。Tcl策略 #Compute1.0e+300/1.0-%puts[expr{1.0e300/1.0e-floating-pointvaluetoolargeto#Compute1.0e+300/1.0-%puts[expr{1.0e300/1.0e-floating-pointvaluetoolargeto那 和彎路是什么#puts"1/2is[expr{1/2}]"puts"-1/2is[expr{-1/2}]"puts"1/2is#puts"1/2is[expr{1/2}]"puts"-1/2is[expr{-1/2}]"puts"1/2is[exprputs"1/3is[exprputs"1/3is[expr 如果你對Tcl工作的細(xì)節(jié)感,下面的輸出q由如下的式子確定aa=q*b+0<=|r|<rhasthesamesignassetsettcl_precision17;#OneofTcl'sfewmagic;#Showalldecimalsneededto;#reproduceaparticularnumberputs"1/2is[expr{1./2}]"puts"1/3is[exprseta[exprputs"3*(1/3)is[exprsetb[exprputs"3*(10/3)is[exprsetc[expr{10.0/3.0}]setd[expr{2.0/3.0}]puts"(10.0/3.0)/(2.0/3.0)is[exprsetsete[exprputs"1.2/0.1is[expr稍微有點意外的是,1/10也出問題了。1.2/0.1結(jié)果是起作用。所以,0.5可以精確表示,但0.1卻不可以。一些實際影響式帶來了很多和影響:##Thewrongwaysetnumber[expr{int(1.2/0.1)}];#Force##Thewrongwaysetnumber[expr{int(1.2/0.1)}];#Forceanintegerfor{seti0}{$i<=$number}{incri{setx[expr... abel}##Arightway-notethelimitset setdeltawhile{$x<1.2+0.5*$delta}... abelsetx[expr{$x+}是,這些標(biāo)準(zhǔn)取決于他們使用哪個國家的——標(biāo)準(zhǔn)和歐洲標(biāo)準(zhǔn)稍微有所不sin(),exp(),根本沒有被標(biāo)準(zhǔn)化。各臺計算機之間的輸出###Twodifferentestimatesof"pi"-onWindows98setpi1[expr{4.0*atan(1.0)}]setpi2[expr{6.0*asin(0.5)}]puts[expr{$pi1-$pi2}]數(shù)值比較101——elseif...?else?truefalse anumeric all 如果測試表達(dá)式返回字符串"yes"/"no""true"/"false",不區(qū)分大小寫。True/FALSEorYeS/nO也是合法的返回值。Falsebody1后面的單詞會被檢查。如果下一個單詞是elseif,那么下一個測試表達(dá)式會被當(dāng)做測試條件。如果下一個單詞是else,那最后的body會被當(dāng)做命令來求值。Ifif求值,而如果是引號,它會在置換階段被求值,然后另一輪置換會在ifsetsetxif{$x==2}{puts"$xis2"}else{puts"$xisnot2"}if{$x!=1}{puts"$xis!=}elseputs"$xis}if$x==1{puts"GOT###Becareful,thisisjustan#Usuallyyoushouldavoidsuchsetyif"$$y!=1"puts"$$yis!=}elseputs"$$yis}##Adangerousexample:duetotheextraroundof#thescriptstopssetyif"$$y!=1"puts"$$yis!=}elseputs"$$yis}文本比較——switch,而不僅僅是整數(shù)。字符串會跟一而不是使用很長的if?elseif?elseif語句。switchstringpattern1body1?pattern2body2?...?patternNbodyN?switchstring{pattern1body1?pattern2body2?...?patternNbodyN?}的模式如果string匹配一個模式那么和那個模式關(guān)聯(lián)的body的代碼就被執(zhí)行。bodyswitch式如果最后一個模式參數(shù)是default字符串,那個模式會匹配任何字符串。這保證了無論string是什么,一些代碼都將會被執(zhí)行。如果沒有default參數(shù),并且任何模式都不匹配string,那么switch命令注意:當(dāng)使用switch和if命令的時候,你可以使用括號來對body參數(shù)分組。這是因為這些命令傳遞他們的body參數(shù)給Tcl解釋器進行求值。這個求值過程包括置換的傳遞,和并不在body參數(shù)內(nèi)的代碼所做的一樣。示例setsetx"ONE"sety1setzONE#Thisisprobablytheeasiestandcleanestformofthe#toswitch$x"$z"sety1[exprputs"MATCH\$z.$y+$zis}ONEsety1[exprputs"MATCHONE.$y+oneissety1[exprputs"MATCHTWO.$y+twoissety1[exprputs"MATCHTHREE.$y+threeis}defaultputs"$xisNOTA}}switch$x"$z"sety1[exprputs"MATCH\$z.$y+$zis}ONEsety1[exprputs"MATCHONE.$y+oneis}TWOsety1[exprputs"MATCHTWO.$y+twois}THREEsety1[exprputs"MATCHTHREE.$y+threeis}defaultputs"$xdoesnotmatchanyofthese}switch$x"ONE""putsONE=1""TWO""putsTWO=2""default""putsNO_MATCH"switch$x "putsONE=1"\ "putsTWO=2" "putsTcl包括兩個循環(huán)命令,即while和for命令。就像if語句,他們求他們測試exprwhile命令,下一節(jié)討論forwhiletesttesttruebody里面的代碼就被執(zhí)行。Body里面的代碼執(zhí)行完成,test被再次求值。Body的continue語句會停止代碼的執(zhí)行,test會被重新求值。Body在Tcl里面,任何東西都是命令,任何東西都經(jīng)歷同樣的置換階段。由于這個原因,test必須被放在括號里面。如果test被放在引號里面,置換階段會把任何變量置換成它們當(dāng)前的值,并傳遞這個test結(jié)果給while命令進行求值。因為test只含有數(shù)字,它的值總是相同的,很可能導(dǎo)致死循環(huán)。示例setsetxThisisanormalwaytowriteaTclwhileloop.while{$x<5}{//正常循環(huán)寫法puts"xissetx[expr{$x+}puts"exitedfirstloopwithXequalto#Thenextexampleshowsthedifferencebetween".."#Howmanytimesdoesthefollowinglooprun?Whydoesit#printoneachsetxwhile"$x5//3次setx[expr{$x+1}]if{$x>7}breakif"$x>3"continueputs"xis$x"}puts"exitedsecondloopwithXequalto102——forfor語法命令語法:這個過程。如果test求值為false,那么循環(huán)會立即退出。Body由于通常你并不想Tcl解釋器在傳遞控制給for命令之前,在置換階段就把變for命令位于同一行,否則Tcl解釋器會把next命令的右大括號當(dāng)做命令的結(jié)束,bodybreakcontinuewhile的使用情況一樣。當(dāng)碰到break時,循環(huán)立即退出。當(dāng)遇到continue時,body的求值停止,test被再次求值。第二個參數(shù),那么默認(rèn)賦給1.示例forfor{seti0}{$i<10}{incr{puts"Iinsidefirst}for{seti3}{$i<2}{incr{puts"Iinsidesecond}seti0while{$i<10}putsputs"Iafterincr:}seti0incri#Thisisequivalentto:seti[expr{$i+1}]添加新令到Tcl——whileTcl當(dāng)proc被求值的時候,它創(chuàng)建一個新命令,名稱是name,參數(shù)是args。當(dāng)name過程被調(diào)用的時候,它就執(zhí)行body的代碼。Proc命令中的body返回值可以用returnReturn命令會返回它的returnbody示例procprocsum{arg1arg2}setx[expr{$arg1+$arg2}];return$x}puts"Thesumof2+3is:[sum23]\n\n"procfor{abc}{puts"Theforcommandhasbeenreplacedbyaputs";puts"Theargumentswere:$a\n$b\n$c\n"}for{seti1}{$i<10}{incr 命令參數(shù)和返回值的里面來作為args中的一個。例如:procproct{a{b1}{c-1}}} 10,這樣會把a設(shè)置為10,而b和c分別保持默認(rèn)值1和-1;justt1020,這樣同樣地設(shè)置b為20,而c還是默認(rèn)值;或者設(shè)置全部三個參數(shù),覆蓋默認(rèn)args。下面的example過程定義了三個參數(shù)。當(dāng)其被調(diào)用時,至少一個參數(shù)必須出現(xiàn)。第二個參數(shù)可以被忽略,這樣它會被賦值為空串。通過args為最后一個參數(shù),example可以接受可變數(shù)量的參數(shù)。注意:如果一個帶默認(rèn)值的變量后面卻跟著一個非args的變量,那這個默認(rèn)值絕不會被使用。例如,如果你這樣一個proc:procfunction{a{b1}c}abTclc但是,你可以可能會沒有值的其他參數(shù),讓他們跟在有默認(rèn)值參數(shù)的后面。例如,下面是有效的:procexample{required{default1a}{default2b}args}{...}在這個例子中,examplerequired。如果有兩以后的所有的參數(shù)都會被賦給args。示例procprocexample{first{second""}{if{$secondeq""}puts"Thereisonlyoneargumentanditis:$first"return1}elseif{$argseq""}puts"Therearetwoarguments-$firstreturn}}elseputs"Therearemanyarguments-$first$secondandreturn}}}setcount1[examplesetcount2[exampleONEsetcount3[exampleONETWOTHREEsetcount4[exampleONETWOTHREEFOUR]//ONEandTWOandTHREEFOURand$count4Arguments"變量作用域——globalTcl對作用域內(nèi)的變量進行求值,這些作用域可以被procs,命名空間(看創(chuàng)建可重用的庫-包和命名空間)或者最的global。Global命令會導(dǎo)致一個局部作用域(過程)的變量那個名稱的全局Upvar命令也是相似的。它把當(dāng)前作用域下的一個變量的名稱關(guān)聯(lián)到一個不同作用域的變量。這通常被用來模擬procs。在其他Tcl代碼里面,你可能也會碰到variable命令。它是命名空間系統(tǒng)的他們的情況。也可以用合適的名為unset令顯式地復(fù)原他們。myVar2?...?otherVarNmyVarN?Upvar命令使myVar1變成了otherVar1的一個,myVar2變成了level等級。默認(rèn)level1,下一級提高。 如果level前綴有“#”,那它 它的就是全局水平的變量。示例procprocSetPositive{variablevalue{upvar$variablemyvarif{$value<0}{setmyvar[expr{-}elsesetmyvar}return}SetPositivexSetPositivey-puts"X:$x Y:$y\n"proctwo{y}{upvar1$yz ;#tiethecallingvaluetovariablezupvar2xa uptoaputs"two:Z:$zA:$a" toconfirmsetz1 ;#Setz,thepassedvariableto1;seta ;#Setx,twolayersup}procone{y}upvar$yz ;#Thistiesthecallingvaluetovariablezputs"one:Z:$z" ;#Outputthatvalue,tocheckitis5twoz changethevalue}oney Yafterthecall.puts"\nX:$xY:procexistence{upvar$variabletestVarif{[infoexiststestVar]}{puts"$variable}elseputs"$variableDoesNot}}setxsetyfor{seti0}{$i<5}{incr{seta($i)}}puts"\ntestingunsettingasimplevariable"#Confirmthatxexists.#Unsetxunsetxputs"xhasbeen#Confirmthatxnolongerexists.existencexTcl101-list(列表List是一個基本的Tcl數(shù)據(jù)結(jié)構(gòu)。一個list是一個簡單的有序集合,可以listTcllist,其中第一項是proclistprocsetlst{{item1}{item2}{itemsplitsetlst[split"item1.item2.item3"用list命令setlst[list"item1""item2""item默認(rèn)是空格。注意:如果有多個splitChars,那么每一個都會獨立地執(zhí)行拆分字符串操作。換句話說,split"1234567""36"會返回下面的列表{12457}index個列表項。注意:01.foreach允許你同時接受多個來自列表的變量:foreach{ab}$listofpairs。你甚至可以同時接受來自多個列表的單個變量。例如:foreacha$listOfAb$listOfBsetsetx"absetsety[split7/4/1776$y0]'thsetz[listputs"arg2is$y"]puts"Acommandresembles:seti0foreachj$x{puts"$jisitemnumber$iinlistx"incri}增加&刪除list(列表)成concat?arg1arg2...連接這些args參數(shù)到一個單獨的列表。它同時去除了args中開頭和結(jié)尾的空白,并在每一個參數(shù)中間添加一個單獨的分隔符。Concat的args參數(shù)可以是單個元素,也可以是list列表。如果一個arg已經(jīng)是list,那它的內(nèi)容會被和其他args連接在一起。lappendlistName?arg1arg2...linsertlistNameindexarg1?arg2...返回一個新的list,即listName的第index個元前入了多個lreplacelistNamefirstlast?arg1...listNameNargsfirst0lreplacefirst當(dāng)你有任意數(shù)目的某種數(shù)據(jù)并且想要按序他們的時候,Tcl中的列表是setsetb[listab{cde}{f{gh}}]puts"Treatedasalist:$b\n"setb[split"ab{cde}{f{gh}}"]puts"Transformedbysplit:$b\n"seta[concatab{cde}{f{gh}}]puts"Concated:$a\n"lappenda{ijKlm} ;#Note:{ijKlm}isasingleelementputs"Afterlappending:puts"Afterlinsertatposition3:setb[lreplace$b35"AA"3:19的的list命令-列表可以用lsearch命令進行搜索,用lsort命令進行排序,用lrange命搜索一個匹配pattern的list項,返回第一個匹配項的下標(biāo),如果沒有匹配項返回-1.默認(rèn)情況下,lsearch使用glob模式進行匹配。查看globbing章有一個list變量,對它排序的方法應(yīng)該這樣:setlst[lsort$lst]。lrangelistfirstlastsetlist[list{Washingtonsetlist[list{Washington1789}{Adams1797}{Jefferson1801}\{Madison1809}{Monroe1817}{Adams1825}setx[lsearch$listWashington*]sety[lsearch$listMadison*]incrxincry-1 ;#Setrangetobesetsubsetlist[lrange$list$xputs"ThefollowingandMadison"foreachitem$subsetlistsservedbetweenputs"Startingin[lindex$item $item0]}setx[lsearch$listsetsetsrtlist[lsortsety[lsearch$srtlistputsscamebeforeMadison簡單的模式匹配-一種通配符匹配技術(shù),大部分Unixs使用它。*?反斜杠在globbing里面對一個特殊字符進行轉(zhuǎn)意,和Tcl樣。使用反斜杠讓你可以使用glob匹配一個*或者?在后面的章節(jié),你會看到glob命令用于 示例##stringmatchf*#stringmatchf??#Doesn'tmatchstringmatchffoo#ReturnsabiglistoffilesonmyDebiansystem.setbins[glob/usr/bin/*]字符串子命令-長度,下標(biāo),范不必使用模糊的名稱的很好的方法。例如,Tcl有stringlength命令而不是,比如slength。這一課包含這些stringstringlengthstringindexstringsetstring"thisismytestputs"Therearesetstring"thisismytestputs"Thereare[stringlength$string]charactersputs"[stringindex$string1]isthesecondcharacterthe5'thand10'th"字符串比較-stringcomparestring1stringfirststring1stringlaststring1stringwordendstringstringmatchpatternsetfullpath"/usr/home/clif/TCL_STUFF/TclTutor/Lsn.17"setrelativepath"CVS/Entries"setfullpath"/usr/home/clif/TCL_STUFF/TclTutor/Lsn.17"setrelativepath"CVS/Entries"setdirectorypathsetpaths[list$fullpath$relativepath$directorypath]foreachpath$paths{setfirst[stringfirst"/"$path]setlast[stringlast"/"$path]#Reportwhetherpathisabsoluteorrelativeif{$first!=0}{puts"$pathisarelative}elseputs"$pathisanabsolute}#If"/"isnotthelastcharacterin$path,reportthelastword.#else,removethelast"/",andfindthenexttolast"/",and#reportthelastincrif{$last!=[stringlength$path]}setname[stringrange$path$lastend]puts"Thefilereferencedin$pathis$name"}elseincrlast-settmp[stringrange$path0$last]setlast[stringlast"/"$tmp]incrlast;setname[stringrange$tmp$lastputs"Thefinaldirectoryin$pathis}#if{[stringmatch"*CVS*"$path]}}##Compareto"a"todeterminewhetherthefirstcharisupperorlowercasesetcomparison[stringcompare$name"a"]if{$comparison>=0}{puts"$namestartswithalowercase}elseputs"$namestartswithanuppercase}}修改字符串-trimChars是空白符(空格,制表符,換行。注意,這些字符不會被當(dāng)做字formatformatString?arg1arg2...返回格式化字符串,方式如同ANSIsprintf過程。formatString是format手冊里面。定義的實際使用的子集是formatString包含字面字母,反斜杠序列和%域。s...d...x...o...f...-... +...示例setupper"THISISASTRINGINUPPERCASEsetlower"thisisastringinlowercaseletters"settrailer"Thisstringhastrailingdots setleader"....Thisstringhasleadingdots"setboth"((thisstringisnestedinparens)))"puts"tolowerconvertsthis:puts" tothis:[stringtolower$upper]\n"puts"toupperconvertsthis:$lower"puts" tothis:[stringtoupper$lower]\n"puts"trimrightconvertsthis:$trailer"puts tothis:[string$trailerputs"trimleftconvertsthis:puts" puts"trimconvertsthis:$both"puts tothis:[stringtrim$bothsetlabels[format"%-20s%+10s""Item"setprice1[format"%-20s%10dCentsEach""Tomatoes""30"]setprice2[format"%-20s%10dCentsEach""Peppers""20"]setprice3[format"%-20s%10dCentsEach""Onions""10"]setprice4[format"%-20s%10.2fperLb.""Steak""3.59997"]puts"\nExampleofformat:\n"puts"$labels"puts"$price1"puts"$price2"puts"$price3"puts正則表達(dá)也有兩個顯式令用于解析正則表達(dá)式regexp?switches?expstring?matchVar??subMatch1... 匹配串的結(jié)尾 匹配前面任意個數(shù)(0-n)的字符(譯者注:表示前面的字符出現(xiàn)0- 次 現(xiàn)1-n次。 匹配該字符集中的任意字符。(...)1618globbing字符集處理的方式。在globbing里面,選擇未知文本集合的唯一方式是符號*”。它匹配任意數(shù)量的字符。字符。例如a*會匹配a,aaaaa,或者空串。如果符號“*”前面緊接的字符是用如,[a-c]*會匹配aa,abc,aabcabc,或者上面的重復(fù)及空串。例如,[a-c]+會匹配a,abc或者aabcabc,但不會是空串。正則表達(dá)式解析比globbingglobbing,你可以使用方括號來Regexp命令和stringmatch命令相似之處在于它匹配一個exp而不是字字符放在matchVar變量里。regexp會拷貝匹配的子字符集串到subSpec參數(shù)里。這可以被用來解析簡單的字符串。Regsub會拷貝字符串的內(nèi)容到一個新的變量,置換匹配exp的字符為被替換成匹配exp的字符。如果反斜杠后面跟著一個1-9的數(shù)字,那么下劃線序列會被替換為圓括號內(nèi)exp適當(dāng)?shù)牟糠?。注意,regexpregsubexpTcl置換過程處理。因此,這個表達(dá)式經(jīng)常包含在括號里,以防止Tcl任何特殊的處理。示例setsetsample"Wherethereisawill,Thereisa##Matchthefirstsubstringwithlowercaselettersonlysetresult[regexp{[a-z]+}$samplematch]puts"Result:$resultmatch:$match"##Matchthefirsttwowords,thefirstoneallowsuppercasesetresult[regexp{([A-Za-z]+)+([a-z]+)}$samplematchsub1sub2]puts"Result:$resultMatch:$match1:$sub12:##Replaceawordregsub"way"$sample"lawsuit"sample2puts"New:$sample2"##Usethe-alloptiontocountthenumberof"words"puts"Numberofwords:[regexp-all{[^]+}25正則表達(dá)式例1.0,1.0,.02,+0.,1,+1,--,+.,-,+.,0.0.1,0..2,andand以有0或多個數(shù)字?;蛟S,[0-9]*\.[0-9]*合適。 和加號。我們讓它為一個空格、制表符或字符串的開頭:^|[\t]。^或制表符(記?。鹤址盶t”表示tab制表符。regexpregexp{.....}$linewholechar_beforenumbernosign##lastcanbeleftoutregexp{.....}$linexxsetsetexamples{"1.0" ".02""+0."如果我們setsetexamples{"1.0" ".02""+0.""" "-"- "0..2""++1"foreache$examplesif{[regexp$pattern$ewholechar_beforenumberdigits_before_period]{puts">>$e<<:$number}elseputs">>$e<<:Doesnotcontainavalid}}>>1.0<<:>>1.0<<:1.0>>.02<<:.02(>>+0.<<:+0.(>>1<<:1>>+1<<:+1>>-0.0120<<:-0.0120(- >>-<<:Doesnotcontainavalid>>+.<<:Doesnotcontainavalid>>0001<<:0001>>0..2<<:Doesnotcontainavalid>>++1<<:Doesnotcontainavalid>>A1.0B<<:Doesnotcontainavalid>>A1<<:Doesnotcontainavalid字符(這里是雙引號),那么”([^”])*”會捕獲雙引號里面的文本。regexpregexp{(["'])[^"']*\1}$stringsetsetstring"Againandagainandagainif{[regexp{(\y\w+\y).+\1}$string=>word]{puts"Theword$wordoccursatleast}(模式\y匹配一個單詞的起始或結(jié)束,\w+指示我們想要至少一個字符###parentheses...if{[regexp-all{(}$string]!=[regexp-all$string]}puts"Parentheses}把他們放進一個列表(-inline選項做這個:setsetparens[regexp-inline-all{[()]}$string]setbalance0setchange("(")1 ;#Thistechniquesavesanif-block:)setchange(")")-foreachp$parensincrbalanceif{$balance<0}puts"Parentheses}}if{$balance!=0}puts"Parentheses}你可以使用VisualRegexpVisualREGEXP應(yīng)用程序?qū)嶒炚齽t表達(dá)式。26陷阱-正則表達(dá)式regexp?switches?expstring?matchVar??subMatch1...regsub?switches?expstringsubSpec求值。這可以提供很多力量,也需要格外。Tcl傳遞一個左括號給正則表達(dá)式解析器來對一系列字符進行求值需要一次轉(zhuǎn)2(Tcl段對括號進行轉(zhuǎn)義,一次在正則表達(dá)式解析里面對括號進行轉(zhuǎn)義。如果你的字用一個反斜杠轉(zhuǎn)義。##Examine##ExamineanoverviewofUNIX/Linuxdiskssetlist1\foreachline$list1puts"$mountedis$size}##Extractingahexadecimalvalue...setline{Interrupt $linematchputs"HexDefaultis:#setstr2regexp"\[^a-f]*def"$str2puts"using\[^a-f]thematchis:regexp"\[a-f^]*def"$str2puts"using\[a-f^]thematchis:regsub{\^}$str2"isfollowedby:"puts"$str2withthe^substitutedis:puts"$str2isconvertedto\"$str3\""27關(guān)聯(lián)數(shù)組(也稱為“哈希”hash表,而其下標(biāo)值是字符串。setname(first)"Mary"setsetname(first)"Mary"setname(last)"Poppins"puts"Fullname:$name(first)除了簡單的和創(chuàng)建數(shù)組令會在下一節(jié)討論之外,這里有幾個數(shù)組命arrayexistsarraynamesarrayNamearraysizearrayget對應(yīng)的數(shù)組元素的值arraysetarrayNamearrayunsetarrayName?inTclandTk里面示例procprocaddname{first{globalincrname(ID)setid$name(ID)setname($id,first)$first ;#Theindexissimplyasetname($id,last) ;#varying}##Initialisethearrayandaddafewnamesglobalnamesetname(ID)0addnameMaryPoppinsaddnameUriahHeepaddnameReneDescartesaddnameLeonardo"da##Checkthecontentsofourdatabase#Theparraycommandisaquickwayto#printit#parray##Somearraycommandsarraysetarray1[list{123}{AbigailAardvark}{234}{BobBaboon}{345}{CathyCoyote}{456}{DanielDog}puts"Array1has[arraysizearray1]puts"Array1hasthefollowingentries:\n[arraynamesarray1]\n"puts"IDNumber123belongsto$array1(123)\n"if{[arrayexistarray1]}{puts"array1isan}elseputs"array1isnotan}if{[arrayexist{puts"array2isan}elseputs"array2isnotan}procexistence{upvar$variabletestVarif{[infoexiststestVar]}{puts"$variable}elseputs"$variableDoesNot}}#Createanfor{seti0}{$i<5}{incri}{seta($i)testputs"\ntestingunsettingamemberofanarray"existencea(0)puts"a0hasbeenunset"unseta(0)existenceanerror"existencea(3)existencecatch{unseta(3)a(0)puts"\nAfterattemptingtodeletea(3),a(0)anda(4)"existencea(3)existenceputs"\nUnsetallthearray'selements"existenceaarrayunsetaputs"\ntestingunsettinganarray"existenceaputs"ahasbeenunset"unsetaexistence28數(shù)組命令-枚舉及其過程中的用foreachname[arraynamesmydata]puts"Dataon\"$name\":}##Getnamesandforeachname[arraynamesmydata]puts"Dataon\"$name\":}##Getnamesandvaluesdirectlyforeach{namevalue}[arrayget{puts"Dataon\"$name\":}foreachforeachname[lsort[arraynames{puts"Dataonprocprint12{putsprocprint12{puts}setarray(1)"A"setarray(2)procprocprint12{upvar$arrayaputs"$a(1),$a(2)"}setarray(1)"A"setarray(2)print12print12示例###Theexampleofthepreviouslessonrevisited-togeta#moregeneral"database"#procaddname{dbfirst{upvar$dbincrname(ID)setid$name(ID)setname($id,first)$first;#Theindexissimplyasetname($id,last) ;#varying}procreport{upvar$db#Loopoverthelastnames:makeamapfromlastnametoIDforeachn[arraynamesname{#SplitthenametogettheID-thefirstpartofthename!#regexp{^[^,]+}$n##Storeinatemporary#an"inverse"mapoflastnametosetsetsettmp($last)}#foreachlast[lsort[arraynames{setidputs"$name($id,first)}}##Initialisethearrayandaddafewnamessetfictional_name(ID)sethistorical_name(ID)addnamefictional_nameMaryPoppinsaddnamefictional_nameUriahHeepaddnamefictional_nameFrodoBagginsaddnamehistorical_nameReneDescartesaddnamehistorical_nameRichardLionheartaddnamehistorical_nameLeonardo"daVinci"addnamehistorical_nameCharlesBaudelaireaddnamehistorical_nameJuliusCaesar##Somesimplereportingputs"Fictionalcharacters:"reportfictional_nameputs"Historicalcharacters:"reporthistorical_name29字典-數(shù)組的替代方arraygetarraysetupvarsetarray(foo,2)setarray(foo,2)setarray(bar,3)這非常簡單,但也可能變得非常笨拙(例如,沒有可的空間。在Tcl8.5里面,dict命令被引入。這提供有效的方式來key-value對。就了字典表示的是鍵到值得,而不是列表的有序的序列。把字典和其他Tcl數(shù)據(jù)結(jié)構(gòu)。例如,你可以創(chuàng)建一個字典的列表,而每這是一個示例(改編自手冊頁面###Createa#Twoclients,knownbytheirclientnumber,#withforenames,surname#dictsetclients1forenamesJoedictsetclients1surnameS dictsetclients2forenamesAnnedictsetclients2surnameOther##Printatableputs"Numberofclients:[dictsize$clients]"dictfor{idinfo}$clients{puts"Client$id:"dictwithinfo{putsputs"Name:$forenames}}—包含兩個鍵”forenames”和”surname”。Dictset命令接受一個鍵名稱的(path套數(shù)據(jù)結(jié)構(gòu)。但是要。直截了當(dāng)?shù)臄?shù)據(jù)結(jié)構(gòu)設(shè)計對于大部分問題來foreach{idinfo}$clients{...dictforforeach{idinfo}$clients{...dictfor命令還是首選的。因為它不僅更有效,而且使我們處理字典而不為了得到著clientID字典里的實際的值,我們使用dictwith命令。如,在我們的例子里,每次外層循環(huán)的info變量會包含一個含有兩個鍵:”forenames”和”surname”的字典。Dictwith命令以與鍵和與字典中關(guān)使用更方便的語法,而不必使用到處dictget。一個相關(guān)令是dict你對這些變量做出的任何改變在dictwith命令完成的時候都會被拷貝回Dictfor循環(huán)返回字典中元素的順序被定義為鍵被添加進字典的時間順序。如果你需要以特定順序這些鍵,那么建議你首先對這些鍵進行顯式地排序。例foreachforeachname[lsort[dictkeys$mydata]]puts"Dataon\"$name\":[dictget$mydata}示例##procaddname{dbVarfirstlast}upvar1$dbVardictincrdbsetid[dictget$db#Createthenewrecorddictsetdb$idfirst$firstdictsetdb$idlast$last}procreport{db}#Loopoverthelastnames:makeamapfromlastnametoIDdictfor{idname}$db#Createatemporarydictionarymap #lastnametoID,forreverselookupif{$ideq"ID"}{continuesetlast [dictget$namelast]dictsettmp$last$id}#foreachlast[lsort[dictkeys{setid[dictget$tmpputs"[dictget$db$idfirst]}}##Initialisethearrayandaddafewnamesdictsetfictional_nameID0dictsethistorical_nameID0addnamefictional_nameMaryPoppinsaddnamefictional_nameUriahHeepaddnamefictional_nameFrodoBagginsaddnamehistorical_nameReneDescartesaddnamehistorical_nameRichardLionheartaddnameaddnamehistorical_nameReneDescartesaddnamehistorical_nameRichardLionheartaddnamehistorical_nameLeonardo"daVinci"addnamehistorical_nameCharlesBaudelaireaddnamehistorical_nameJuliusCaesar##Somesimplereportingputs"Fictionalcharacters:"report$fictional_nameputs"Historicalcharacters:"report$historical_nameupvar來連接它,正如我們前面對數(shù)組所做的那返回一個新的字典值(upvarreport過程里,30文件借助gets和puts。但是,當(dāng)有很多數(shù)據(jù)去讀得時候,有時,使用read命令來加載整個文件,然后通過split命令將文件解析成行會更有效。擬文件系統(tǒng)”使用內(nèi)存里面的文件而不是硬盤上的。Tcl提供一個幾乎統(tǒng)一的接(token 長度為0. permission是一個整數(shù),用來設(shè)置文件的權(quán)限。默認(rèn)是getsfileID(newlineputs?-nonewline??fileID?fileID中全部剩余的字節(jié),并返回這個字符串。如果-nonewline(newline條件在read命令執(zhí)行之前都會被清除。readfileIDOffset是一個當(dāng)前將要被設(shè)置的位置的偏移字節(jié)數(shù)。偏移起始測量位置默認(rèn)為文件開始,但也可以從當(dāng)前位置開始,或者通過適當(dāng)設(shè)置origin為文件末尾。Start…….Offset從文件開始進量current…….Offsetend…….OffsetlTcl文件需要記住的幾點:setstring[gets你不能重寫任何以a權(quán)限打開的文件中的數(shù)據(jù)。但是,你可以找到文件的開始用于gets命令。w+權(quán)限打開文件允許你重寫數(shù)據(jù),但會刪除全部現(xiàn)有的文件中的數(shù)進制”文件,你必須使用fconfigure命令。釋,然后再source這個文件。示例###Countthenumberoflinesinatextfilesetinfile[open"myfile.txt"r]setnumber0###getswithtwoargumentsreturnsthelengthoftheline,#-1if ofthefileisfound#while{[gets$infileline]>=0{incr}closeputs"Numberoflines:$number"#Alsoreportitinanexternalfilesetoutfile[open"report.out"puts$outfile"Numberoflines:$number"close$outfile文件信息-有兩個命令提供文件系統(tǒng)的信息,gl
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 專業(yè)教育培訓(xùn)終身支持承諾書(3篇)
- 健康促進措施有效執(zhí)行保證承諾書范文9篇
- 環(huán)保可持續(xù)與綠色發(fā)展承諾書7篇
- 能源環(huán)保技術(shù)研發(fā)與成果保護承諾書(9篇)
- 環(huán)保話題的議論作文8篇
- 內(nèi)部質(zhì)量管控責(zé)任承諾書4篇
- 落實反欺詐措施承諾書范文5篇
- 公益捐款定向使用承諾書(4篇)
- 企業(yè)質(zhì)量誠信保證承諾書9篇
- 網(wǎng)絡(luò)信息安全保障措施承諾書范文4篇
- 美術(shù)教學(xué)中的跨學(xué)科教學(xué)策略
- 羅茨鼓風(fēng)機行業(yè)發(fā)展趨勢報告
- 慢性阻塞性肺疾病患者非肺部手術(shù)麻醉及圍術(shù)期管理的專家共識
- 燈謎大全及答案1000個
- 中建辦公商業(yè)樓有限空間作業(yè)專項施工方案
- 急性胰腺炎護理查房課件ppt
- 初三數(shù)學(xué)期末試卷分析及中考復(fù)習(xí)建議課件
- GB/T 4074.8-2009繞組線試驗方法第8部分:測定漆包繞組線溫度指數(shù)的試驗方法快速法
- 人教版四年級上冊語文期末試卷(完美版)
- 防空警報系統(tǒng)設(shè)計方案
- 酒店管理用水 酒店廚房定額用水及排水量計算表分析
評論
0/150
提交評論