Tcl_1_2015.00_LG_03 S公司2015年tcl教程Lab guide
- 格式:pdf
- 大小:453.37 KB
- 文档页数:17
TCL 培训教程(全)(仅供内部使用)深圳市华为技术有限公司版权所有侵权必究深圳市华为技术有限公司研究管理部文档中心文档编号产品版本密级共76页拟制:陈旭盛日期:2000/12/08审核:日期:yyyy/mm/dd 审核:日期:yyyy/mm/dd 批准:日期:yyyy/mm/dd修订记录日期修订版本描述作者2000/12/08 2.00初稿完成陈旭盛目录1引言6 2语法72.1脚本、命令和单词符号72.2置换(substitution)72.2.1变量置换(variable subtitution)82.2.2命令置换(command substitution)82.2.3反斜杠置换(backslash substitution)82.2.4双引号和花括号92.3注释93变量103.1简单变量103.2数组113.3相关命令113.3.1set113.3.2unset113.3.3append和incr124表达式124.1操作数124.2运算符和优先级124.3数学函数135List145.1list命令145.2concat命令:145.3lindex命令155.4llength命令155.5linsert命令155.6lreplace命令:155.7lrange命令:155.8lappend命令:155.9lsearch命令:165.10lsort命令:165.11split命令:165.12join命令176控制流176.1if命令176.2循环命令:while、for、foreach176.2.1while命令176.2.2for命令186.2.3foreach命令186.2.4break和continue命令196.2.5switch命令196.1eval命令196.2source命令19 7过程(procedure)207.1过程定义和返回值207.2局部变量和全局变量207.3缺省参数和可变个数参数217.4引用:upvar21 8字符串操作228.1format命令228.2scan命令238.3regexp命令238.4regsub命令258.5string命令258.5.1string compare?-nocase??-length int?string1string2258.5.2string equal?-nocase??-length int?string1string2258.5.3string first string1string2?startindex?268.5.4string index string charIndex268.5.5string last string1string2?startindex?268.5.6string length string268.5.7string match?-nocase?pattern string268.5.8string range string first last278.5.9string repeat string count278.5.10string replace string first last?newstring?278.5.11string tolower string?first??last?278.5.12string toupper string?first??last?278.5.13string trim string?chars?278.5.14string trimleft string?chars?278.5.15string trimright string?chars?27 9文件访问289.1文件名289.2基本文件输入输出命令289.3随机文件访问299.4当前工作目录309.5文件操作和获取文件信息30 10错误和异常3310.1错误3310.2从TCL脚本中产生错误3410.3使用catch捕获错误3510.4其他异常35 11深入TCL3711.1查询数组中的元素3711.2info命令3811.2.1变量信息3811.2.2过程信息3911.2.3命令信息4011.2.4TCL的版本和库4111.2.5命令的执行时间4111.2.6跟踪变量4111.2.7命令的重命名和删除4311.2.8unknown命令4411.2.9自动加载44 12历史记录45 13TCL和C\C++4713.1生成自己的TCLSH4813.2扩展自己的命令:方法(一)4813.2.1编写扩展命令对应的C/C++过程4813.2.2注册命令4913.2.3命令返回值和命令对应的过程的返回值5013.3扩展自己的命令:方法(二)5213.3.1Tcl_Obj结构5213.3.2编写扩展命令对应的C/C++过程5413.3.3注册命令5413.4利用clientData参数和deleteProc参数5513.5在C/C++应用程序中嵌入TCL58 14总结59TCL 培训教程(全)关键词:TCL 摘要:本文是TCL 教材的第三稿,前两稿分别是《TCL 的使用》和《TCL 培训教程》。
目录•TCL基础概念与特点•TCL基本语法与数据结构•TCL过程与函数定义调用•TCL扩展功能库使用指南•TCL界面编程技术实践•TCL网络编程应用实例•TCL测试与调试技巧分享TCL基础概念与特点01TCL(Tool Command Language)是一种广泛应用的嵌入式脚本语言。
02发展历程:起源于20世纪80年代,由John Ousterhout教授创建,至今仍在不断更新和发展。
03主要应用于快速原型开发、自动化测试、GUI应用程序等领域。
TCL定义及发展历程TCL语言特性与优势01语言特性简单易学、动态类型、面向对象、可扩展性强。
02优势跨平台兼容性好,易于与C/C等语言集成,提供丰富的库函数和工具。
应用领域及案例分析应用领域自动化测试、网络编程、嵌入式系统开发等。
案例分析如使用TCL进行自动化测试脚本编写,提高测试效率;在嵌入式系统中利用TCL实现动态配置和功能扩展。
开发环境与工具介绍开发环境支持多种操作系统,如Windows、Linux、macOS等。
工具介绍常用的开发工具有Tclsh、Tk、Expect等,分别用于命令行交互、GUI开发和自动化控制。
TCL基本语法与数据结构变量、数据类型与运算符01变量声明与赋值TCL中变量无需事先声明,直接使用`set`命令进行赋值,例如`set x10`。
02数据类型TCL支持多种数据类型,包括整数、浮点数、字符串等。
数据类型之间可以自动转换。
03运算符TCL支持常见的算术运算符(如+、-、*、/)、比较运算符(如==、!=、<、>)和逻辑运算符(如&&、||)。
循环结构TCL提供`for`和`foreach`循环结构,用于重复执行某段代码。
其中,`for`循环可以指定循环次数和步长,`foreach`循环则遍历列表或数组中的元素。
条件语句TCL中使用`if`、`elseif`和`else`关键字构成条件语句,根据条件执行不同的代码块。
Tcl编程简介(一)简介 Tcl是一种很通用的脚本语言,它几乎在所有的平台上都可以解释运行,功能强大。
是tool command language的缩写,发音为 "tickle”,实际上包含了两个部分:一个语言和一个库。
首先,Tcl是一种简单的脚本语言,主要使用于发布命令给一些互交程序如文本编辑器、调试器和shell。
它有一个简单的语法和很强可扩充性,Tcl可以创建新的过程以增强其内建命令的能力。
其次,Tcl是一个库包,可以被嵌入应用程序,Tcl的库包含了一个分析器、用于执行内建命令的例程和可以使你扩充(定义新的过程)的库函数。
应用程序可以产生Tcl命令并执行,命令可以由用户产生,也可以从用户接口的一个输入中读取(按钮或菜单等)。
但Tcl库收到命令后将它分解并执行内建的命令,经常会产生递归的调用。
下面简单介绍以下tcl的语法规则:解释器 在Tcl的数据结构中的核心是Tcl_Interp.一个解释器包含了一套命令,一组变量和一些用于描述状态的东西。
每一个 Tcl命令是在特定的Tcl_Interp中运行的,基于Tcl的应用程序可以同时拥有几个Tcl_Interp。
Tcl_Interp是一个轻量级的结构,可以快速的新建和删除。
数据类型 Tcl只支持一种数据结构:字符串(string)。
所有的命令,命令的所有的参数,命令的结果,所有的变量都是字符串。
请牢记这一点,所有的东西都是字符串。
这是它比较有特点的方面字符串有三种形式:命令(command), 表达式(expresion)和表(list)。
Basic Command Syntax 基本语法 Tcl有类似于shell和lisp的语法,当然也有许多的不同。
一条Tcl的命令串包含了一条或多条命令用换行符或分号来隔开,而每一条命令包含了一个域(field)的集合,域使用空白分开的,第一个域是一个命令的名字,其它的是作为参数来传给它。
例如: set a 22 //相当于C中的 a=22 a是一个变量这条命令分为三个域:1 set 2 a 3 22 set使用于设置变量的值的命令,a、20 作为参数来传给它,a使它要操作的变量名,22是要付给的a值。
Tcl编程教程第一部分:基础知识```tclputs "Hello, Tcl!"```将文件保存为`hello.tcl`。
在命令行中,使用以下命令运行这个程序:```bashtclsh hello.tcl```你将看到输出`Hello, Tcl!`。
3. 变量:在Tcl中,你可以使用`set`命令创建变量。
例如:```tclset name "John"puts $name```输出将会是 `John`。
4. 字符串操作:Tcl提供了许多可以操作字符串的内置命令。
例如,你可以使用`string length`命令来获取字符串的长度:```tclset str "Hello, World!"set len [string length $str]puts "String length: $len"```输出将会是 `String length: 13`。
5. 数字操作:除了操作字符串,Tcl还支持对数字的操作。
你可以使用`expr`命令来进行数学运算:```tclset num1 10set num2 5set sum [expr $num1 + $num2]puts "Sum: $sum"```输出将会是 `Sum: 15`。
第二部分:条件和循环1. 条件语句:在Tcl中,你可以使用`if`语句来进行条件判断。
例如:```tclset num 10if {$num > 0}puts "Positive"} elseif {$num < 0}puts "Negative"} elseputs "Zero"```输出将会是 `Positive`。
2. 循环语句:Tcl中有两种常见的循环语句,`while`循环和`foreach`循环。
TCL编程高级教程本教程将介绍一些TCL编程的高级概念和技巧,以帮助读者更好地理解和应用TCL语言。
1. 过程(Procedure)和命名空间(Namespace):TCL中的过程类似于其他编程语言中的函数,用于封装一段特定的逻辑。
过程可以接受参数,并返回结果。
命名空间用于隔离变量和过程,以避免命名冲突。
2. 错误处理:TCL提供了异常处理机制,可以在代码中捕获和处理错误。
使用catch命令可以捕获异常,并使用error命令主动抛出异常。
3.文件操作:TCL提供了一组用于文件操作的命令,包括打开、读取、写入和关闭文件等。
可以使用文件操作命令来读取和写入文本文件,进行文件系统的管理和文件的复制等操作。
4.正则表达式:TCL支持使用正则表达式进行字符串匹配和替换。
正则表达式提供了一种强大的模式匹配工具,可以用于解析文本、过滤数据和提取信息等操作。
5. 并发编程:TCL提供了一些并发编程的工具,可以启动多个线程并进行并行计算。
使用thread命令可以创建和管理线程,使用事件循环来处理线程之间的同步和通信。
6. 扩展和集成:TCL支持通过扩展库来增加语言的功能。
可以使用load命令加载扩展库,并使用扩展库提供的命令和函数来进行更复杂的编程任务。
7. 调试和性能优化:TCL提供了一些调试工具,可以用于跟踪和调试代码的执行过程。
可以使用puts命令来打印调试信息,使用trace命令来对变量和过程的修改进行追踪。
此外,可以使用一些性能优化技巧,如缓存变量、避免重复计算、使用原生命令等,来提高代码的执行效率。
总结起来,本教程介绍了TCL编程的一些高级概念和技巧,包括过程和命名空间、错误处理、文件操作、正则表达式、并发编程、扩展和集成以及调试和性能优化等方面。
通过学习这些内容,读者可以更加灵活和高效地使用TCL语言来完成各种编程任务。
Play with Strings3and ListsPlay with Strings and Lists Lab 3-1Lab 3Lab 3-2 Play with Strings and ListsThe Power of Tcl 1: Becoming a Proficient Tcl UserLab OverviewDuring this lab, you will build a broad and useful command repertoire formanipulating strings and lists.Answers & SolutionsThis lab guide contains answers and solutions to all questions. If you need help answering a question or would like to confirm your results, check the back portion of this document. Lab TasksCreate a useful command while applyingthe commands learned in lectureLAB 2Learn skills that will be essential everytime you write Tcl scriptsLAB 3Master the commands to count patterns instrings, and gain comfort with the basiccomponents of a Tcl scriptLAB 1Lab 3 File LocationsDirectory Structuredesign_data ORCA netlistscripts Constraint and run scriptslibs Technology librariestcl_procs Tcl procedures and solutions.synopsys_pt.setup PrimeTime setup file.synopsys_dc.setup Design Compiler setup fileRelevant Filesscripts/rpt_TNV.tcl Incomplete TNV commandrun.tcl Reads the ORCA designtcl_procs/rpt_TNV.tcl Full TNV solution for homeworklist_sub.tcl Solution for Q25 in Task 5pin_match.tcl Solution for Q26 in Task 5Play with Strings and Lists Lab 3-3 The Power of Tcl 1: Becoming a Proficient Tcl UserLab 3Lab InstructionsTask 1.Playing With Tcl StringsBefore applying strings to real world examples, you will go through some basicexamples to gain an understanding of what strings are all about.The skills learned will be useful in the future whenever you explore new Tclcommands or forget how to use commands you learned in the past.1.Invoke either Design Compiler or PrimeTime.There is no need to read a design for the following exercises.All subsequent instructions are generic for either tool - DesignCompiler or PrimeTime.1.Create two strings by executing the following commands.e the command regexp –all to count patterns in a string.Question 1. How many letter l’s are in the string captured by variable a(you should get 3)?....................................................................................................Question 2. How many newlines in the string captured by variable b (youshould get 2)?.................................................................................................... Lab 3-4 Play with Strings and ListsThe Power of Tcl 1: Becoming a Proficient Tcl UserLab 33.Count the total number of characters in a string using the command stringlength. Execute the following example.Question 3. Did the above exercise confirm that spaces and newlinescount as individual characters in strings?....................................................................................................4.Determine if a string matches a pattern using globbing and the commandstring match.For string matching to succeed (i.e. the return value is 1), the pattern and thestring must be identical except that the pattern may include wildcardcharacters such as *.Question 4. Did the above commands work as expected?....................................................................................................5.Extract characters from a string using the command string index.Question 5. Does the index range start at 1 or 0 (i.e. to get the firstcharacter in a string, do you use an index of 1 or 0)?....................................................................................................Question 6. Do you need to know the total number of characters in astring to extract the LAST character of the string?.................................................................................................... Play with Strings and Lists Lab 3-5 The Power of Tcl 1: Becoming a Proficient Tcl UserLab 3Question 7. From your own experimentation, what will string indexreturn if you provide an index outside the range of theprovided string argument?....................................................................................................e the string command to find the index of the last \nt (a newline followedby the letter t) in the string captured by the variable b.Use the relevant portion of the man page for the string command shownbelow.string last string1 string2Search string2 for a sequence of characters that exactly match thecharacters in string1. If found, return the index of the firstcharacter in the last such match within string2. If there is nomatch, then return -1.Question 8. What is the index of the first character of the last \nt in thestring captured by variable b?....................................................................................................7.Append strings using the append command.Question 9. After executing the above command, was the value ofvariable a modified?....................................................................................................Question 10. Does the append command add spaces when it concatenatesstrings?....................................................................................................8.Visually identify the string commands used so far on job aid #1.Lab 3-6 Play with Strings and ListsThe Power of Tcl 1: Becoming a Proficient Tcl UserLab 3 Task 2.Playing With Tcl ListsPerform the same type of exercises with Tcl lists.1.Create two Tcl lists by executing the following lines.2.Count the total number of elements in each list using the Tcl commandllength.Question 11. Explain why the last example above returned a value of 1?....................................................................................................Question 12. Do spaces count as individual list elements?....................................................................................................3.Play with list indices. Extract list elements using the command lindex.Question 13. Write the command to extract the last element from a list.Use your experience with string indices, or use the man pagefor lindex..................................................................................................... Play with Strings and Lists Lab 3-7 The Power of Tcl 1: Becoming a Proficient Tcl UserLab 3Lab 3-8 Play with Strings and ListsThe Power of Tcl 1: Becoming a Proficient Tcl User4.Determine if any list element matches a pattern using lsearch –glob .Question 14. What does lsearch –glob return if the match is successful and what does it return if the match is NOT successful? .................................................................................................... 5.Insert items into a list using the command linsert . Question 15. Did the above command modify the variable b ? .................................................................................................... Question 16. Rewrite the above command such that the value of variable b is modified to be "zero one two three". .................................................................................................... 6.Append lists together using the command lappend .Question 17. After executing the first command above, was the value of variable b modified? .................................................................................................... Question 18. Does lappend add spaces when appending elements to a list? .................................................................................................... Question 19. Can individual list elements themselves be lists? ....................................................................................................Lab 37.Iterate over every element of a list using the command foreach.Question 20. How many times does the foreach command iterate?....................................................................................................Question 21. What is the user defined variable list_element set to duringeach iteration?....................................................................................................8.Visually identify the list commands used so far on job aid #1.Task 3.Convert Strings Into Lists and Back AgainFor the last exercise, perform the same type of “hello world” exercises converti ngstrings to lists and back to strings.1.Create two strings by executing the following command.2.Convert a string to a list using the split command.Question 22. Do the splitChars remain in the resulting list?....................................................................................................Question 23. Do spaces from the original string remain in the resulting list?.................................................................................................... Play with Strings and Lists Lab 3-9 The Power of Tcl 1: Becoming a Proficient Tcl UserLab 33.Convert a list back to a string using the join command.Question 24. Describe the result of the last command executed above.....................................................................................................4.Quit the Synopsys tool and return to lecture. This completes the workshoplabs.Task 4.Optional Homework: Complete rpt_TNV.tclPlease look at the foils in the appendix of Unit 4 for a description of the problemyou will be solving in this task.1.Invoke either Design Compiler or PrimeTime using the script ./scripts/run.tcl2.Play with your starting point by sourcing the procedure contained in./scripts/rpt_TNV.tcl and executing the command rpt_TNV.3.Edit the procedure in ./scripts/rpt_TNV.tcl such that the total number ofviolations is reported for each individual group (each clock group as well aseach group of design rule violations).One example solution is contained in ./tcl_procs/rpt_TNV.tcl Task 5. Writing Custom ScriptsQuestion 25. Write a Tcl script to subtract list_2 elements from list_1 elements(i.e. list1 – list 2) (Create list1 to be “dc pt mw icc1” and list2 to be “pt icc2 mw”)……………………………………………………………………Question 26. Write a Tcl script to check if a pin exists in the input list, and if soreport the net to which it is connected. (The input list is given as“I_ORCA_TOP/pad_in[10] I_ORCA_TOP/pad_in[5]I_ORCA_TOP/sd_DQ_in[11]”)……………………………………………………………………..Lab 3-10 Play with Strings and ListsThe Power of Tcl 1: Becoming a Proficient Tcl UserAnswers / SolutionsTask 1.Playing with Tcl StringsQuestion 1. How many letter l’s are in the string captured by thevariable a?Question 2. How many newlines are in the string captured by thevariable b?Question 3. Did the above exercise confirm that spaces and newlinescount as individual characters in strings?Yes. The command string length will count everycharacter in a string, which includes newlines and spacesrepresenting a single character. The double quotes that wereused to create the string in the first place are not part of theactual string and are not counted in the string length.Question 4. Did the above commands work as expected?The first command succeeds because the pattern completelymatches the string.The second command fails. The pattern and the string mustbe identical. The pattern two* does not completely matchthe string! The following example will return a successfulmatch (notice the wildcard * matches newlines as well).Question 5. Does the index range start at 1 or 0 (i.e. to get the firstcharacter in a string, do you use an index or 1 or 0)?0. You will notice later that this is consistent with listindexing as well.Lab 3-12 Play with Strings and ListsQuestion 6. Do you need to know the total number of characters in astring to extract the LAST character of the string?No. You can use the string index end to extract the lastcharacter.Question 7. From your own experimentation, what will string indexreturn if you provide an index outside the range of theprovided string argument?The command returns the empty string.Question 8.What is the index of the first character of the last \nt in thestring captured by variable b ?Question 9. After executing the above command, was the value ofvariable a modified?Yes. Certain commands ask for the variable name and willmodify the variable value. Other commands will modify thestring itself (not the variable). To confirm, use printvar asshown below. Also shown is the relevant portion of theman page where it clearly asks for the variable itself.printvar a→ a = "hello worldonetwothree"man appendNAMEappend - Append to variable SYNOPSISappend varName ?value value value ...?DESCRIPTIONAppend all of the value arguments to the current value of variable varName.Question 10. Does the append command add spaces when it concatenatesstrings?No, it does not.Task 2.Playing with Tcl ListsQuestion 11. Explain why the last example above returned a value of 1.The last command returns the length of the list “b” whichhas one list element (named b). Notice this is different fromthe second to last command which is using the value of thevariable named b (which is set to "one two three" and hasthree list elements).Question 12. Do spaces count as individual list elements?Spaces are used to separate list elements and are not countedas list elements themselves. If you wanted to include aspace as a list element, you will have to do something likethe following example.Question 13. Write the command to extract the last element from a list.Use your experience with string indices, or use the manpage for lindex.String and list indices are consistent. Following is thecorrect command and the relevant portion of the man page. lindex $a endman lindex. . . If index has the value end, it refers to the last element in the list, and end-integer refers to the last element in the list minus the specified integer offset.Question 14. What does lsearch –glob return if the match is successfuland what does it return if the match is NOT successful?This command returns the list index of the 1st matching listelement if successful (recall the first list index starts at 0!).It returns –1 if not successful. This matches the relevantportion of the man page shown below.DESCRIPTIONThis command searches the elements of list to see if one of themmatches pattern. If so, the command returns the index of the first matching element. If not, the command returns -1.Question 15. Did the above command modify the variable b?No, the variable b is still “one two three”.Question 16. Rewrite the above command such that the value of variableb is modified to be "zero one two three".Question 17. After executing the first command above, was the value ofvariable b modified?Yes, in this example the variable b WAS modified. Useprintvar to validate this.Question 18. Does lappend add spaces when appending elements to alist?Spaces are used to separate elements in a list. Therefore,lappend MUST add spaces when appending list elements. Lab 3-14 Play with Strings and ListsQuestion 19. Can individual list elements themselves be lists?Yes. This is shown in the last example as shown below.The list captured by the variable b is appended to a as asingle list element.Question 20. How many times does the foreach command iterate?In this example, 3 times – once for every list element in a. Question 21. What is the user defined variable list_element set to during each iteration?It is set to each subsequent item in the original list a. Theresult of the foreach iteration is shown below.Task 3.Convert Strings Into Lists and Back Again Question 22. Do the splitChars remain in the resulting list?No, they do not. The splitChars are removed as well asidentify where the original string should be split into theresulting list.Question 23. Do spaces from the original string remain in the resultinglist?Yes they do. If an individual list element contains spaces, itwill be shown with { } to identify it as a single list elementas shown in the example below.# The o is removed from the resulting list# The space in the original list is part of the second list element# The resulting list contains 3 list elementssplit $a o→ hell { w} rld# A different example.# Notice the space is kept as part of the second list elementsplit $a e→ h {llo world}# Notice now that space is used as a splitting element# The space is removed and the resulting list is split accordinglysplit $a "e "→ h llo worldQuestion 24. Describe the result of the last command executed above.The final result is a string where all letter o’s in the origina lstring are replaced by the number 5.Task 5. Writing Custom ScriptsQuestion 25. Write a Tcl script to subtract list_2 elements from list_1 elements(i.e. list1 – list 2)proc list_sub { lis1 lis2 } {set result ""foreach el $lis1 {if {[lsearch -exact $lis2 $el] == -1} {lappend result $el}}return $result}Lab 3-16 Play with Strings and ListsQuestion 26. Write a Tcl script to check if a pin exists in the input list, and if so report the net to which it is connected. (The input list is given as “I_ORCA_TOP/pad_in[10]I_ORCA_TOP/pad_in[5] I_ORCA_TOP/sd_DQ_in[11]”)set my_pins [list I_ORCA_TOP/pad_in[10] I_ORCA_TOP/pad_in[5]I_ORCA_TOP/sd_DQ_in[11]]proc match_pins { pin_name } {global my_pinsif {[lsearch -exact $my_pins $pin_name ] != -1} {set net [get_object_name [get_attribute [get_pins $pin_name -quiet] net]]puts "The pin $pin_name is connected to the net $net"} else {puts "No pin found"}}Note: In the above script try replacing the “-exact” switch with “-glob” or “-regexp” and check what the script outputs.。