Вы находитесь на странице: 1из 54

Tcl Tutorial

Outline
T T cl utorial Outline W hat is T ? cl W hat is T ? k W is T that successf ? hy cl ul W hen using T ? cl W is T better than ...? hy cl T Extensions cl Getting started Example ! Compute f actorial T Fundamentals cl T Basics cl Comments Mathematical Expressions Control Structures Strings Lists Arrays Procedures F ile-IO W ildcards (glob) Regular expressions Error handling Dif erent stuf f f Advanced Concepts T CL-Ref erence T & EDA Market cl

Tcl Tutorial

Oct-2000

- Slide 2 -

What is Tcl ?
Tool Command Language ( " tickle # ) Scripting language simple syntax Library package can be embedded in applications language parser build in commands extensible

Tcl Tutorial

Oct-2000

- Slide 3 -

What is Tk ?
Graphical user interface toolkit. Tk is portable. Tk is easy to use. Tk allows rapid development. Tk implements platform look and feel on UNIX, Windows and Mac. lsivega graphical user interface is 1 00% Tk.

Tcl Tutorial

Oct-2000

- Slide 4 -

Why is Tcl that successful ?


Tcl provides programmability. Tcl application needs to implement only application specific low level commands. Tcl is a Vendor independent standard. Tcl is easy to learn. Tcl is a complete language. Tcl is complete royalties free. Tcl and Tk are highly portable. Tcl supports rapid development. Tcl makes your application extensible.
Tcl Tutorial Oct-2000

- Slide 5 -

When using Tcl ?


Philosophy " large software should use two languages # :
1.

system language manipulating complex internal data structures performance is key

2.

scripting language tie pieces together provide user interface

Tcl Tutorial

Oct-2000

- Slide 6 -

Why is Tcl better than ...?


F e a tu re s Sp eed o f u se ( w w w . s c rip tic s . c o m ) Ra p id d e ve lo p m e n t F le xib le , ra p id e v o l u ti o n I n te r a c ti v e S h e l l G re a t re g u la r e x p re s s i o n s E a s i l y e x te n s i b l e E m b e d d a b le Ea sy G U Is I n te r n e t re a d y E n te rp ris e u sa g e C r o s s p l a tfo rm T h r e a d s a fe D a ta b a s e a c c e s s O b j e c t o ri e n te d M a i n ta i n a b i l i ty (iTcl) (Tk) (Tk) Tcl P e rl P y th o n Java S c rip t Visu a l B a sic

B re a d th o f fu n c t i o n a l i t y

Tcl Tutorial

Oct-2000

- Slide 7 -

Tcl Extensions
Graphical user interface Object system Automating interactive applications Networking Database access

Tcl Tutorial

Oct-2000

- Slide 8 -

Getting started
How to make run-able Tcl scripts: Create a text file which starts with #!<path to>/tclsh or if Tk is needed #!<path to>/wish Or if the path to the Tcl interpreter is unknown
#! /bin/sh # following line is a comment for Tcl but not for sh # \ exec tclsh $ 0 " $@ #

Make your script executable (chmod) Or source your script in a tclsh/wish


tclsh source my_script. tcl

Tcl Tutorial

Oct-2000

- Slide 9 -

Example ! Compute factorial


proc factorial { x } { set product 1 for { set i 1 } { $i <= $x } { incr i } { set product [ expr { $ product * $ i } ] } return $product

proc factorial_recursive { x } { if { $x == 1 } { return 1 } else { return [ expr { $x * \ [ factorial_recursive [ expr { $x -1 } ] ] } ] } } puts " fact( 10) = [ factorial 10 ] # puts " fact( 10) = [ factorial_recursive 10 ] "
Tcl Tutorial Oct-2000 - Slide 1 0 -

Tcl Fundamentals
String based language - Everything is a string ! Only a few constructs. Simple syntax. Tcl is interpreted. Tcl knows only two language constructs: commands variables

Tcl Tutorial

Oct-2000

- Slide 1 1 -

Tcl Basics
The concept of Tcl is a little different than other languages it$ s worth to understand the basic concepts ! Variables Commands Grouping Substitution Command call
Tcl Tutorial Oct-2000

- Slide 1 2 -

Tcl Basics - Variables


Set command is used to assign a value
set variable 2000 puts $ var

The dollar sign $ is used to obtain the value from a variable. Case is significant for variable names. Variable names can contain any character and be of any length. Variables defined outside any procedure are global variables. Global variables are not automatically visible inside procedures. -> use global variable-name to make them accessible Variables don $ t need to be declared.
Tcl Tutorial Oct-2000

- Slide 1 3 -

Tcl Basics - Commands


A Tcl script is a sequence of commands. Basic syntax for a Tcl command:
command-name arg1 arg2 arg3 . . .

White spaces (space or tabs) separate command name and arguments. Newline or semicolon terminates a command. A command returns one string.

Tcl Tutorial

Oct-2000

- Slide 1 4 -

Tcl Basics - Grouping


Curly braces { } prevent substitution. Double quotes " # allow substitution. \ escapes white spaces (space, tabs, newlines). Braces { } and quotes " # are not part of the value.

Tcl Tutorial

Oct-2000

- Slide 1 5 -

Tcl Basics - Substitution


Backslash substitution \ Quotes special characters literally. Specify hexadecimal or octal values. Variable substitution $ Substitute variable by value.
puts $var set a \$bc; puts $ a ; # -> $ bc

Command substitution [ ] Nesting commands.


puts [ string length " Hi lsiVega# ]
Tcl Tutorial Oct-2000

- Slide 1 6 -

Tcl Basics - Execution


Execution calls the command passing all arguments. Command returns a value or an error.

Tcl Tutorial

Oct-2000

- Slide 1 7 -

Example ! Compute factorial


proc factorial { x } { set product 1 for { set i 1 } { $i <= $x } { incr i } { set product [ expr { $ product * $ i } ] } return $product

proc factorial_recursive { x } { if { $x == 1 } { return 1 } else { return [ expr { $x * \ [ factorial_recursive [ expr { $x -1 } ] ] } ] } } puts " fact( 10) = [ factorial 10 ] # puts " fact( 10) = [ factorial_recursive 10 ] "
Tcl Tutorial Oct-2000 - Slide 1 8 -

Comments
Comments in Tcl starts with the hash character #. The hash character must occur at the beginning of a command. The semicolon ; can be used to terminate the previous command.
set a 1 ; # I $ m a comment

Comments can be continued to the next line escaping the newline


# I $ m a long \ comment

Tcl Tutorial

Oct-2000

- Slide 1 9 -

Mathematical Expressions
Evaluation of a mathematical expression
expr arg arg . . .

All arguments are concatenated together and evaluated as a Tcl expression. Expressions are subject of two rounds of substitutions! one by the Tcl interpreter one by expr itself protect expressions with curly braces

Tcl Tutorial

Oct-2000

- Slide 20 -

Mathematical Expressions
Works with boolean, integer, double and strings. +-*/% ~&|^ ! && || << >> < > <= >= == != ?:

sin cos tan abs log sqrt ... Examples


expr expr expr expr expr expr { { { { { { 5 / 4 } ; # -> 5 / 4. 0 } ; # -> 5 / ( 4 + 0. 0 ) } ; # -> " a# == " g# } ; # -> a == g } ; # -> asin( 1) * 2 } ; # ->
Tcl Tutorial Oct-2000

1 1. 25 1. 25 0 syntax error 3. 14159265359

- Slide 21 -

Control Structures
Conditional commands
if then else switch

Loops
while for foreach break, continue

Others
return, error, catch
Tcl Tutorial Oct-2000

- Slide 22 -

Control Structures - Conditional Cmd


if: if test1 body1 elseif test2 body2 % else body3
if { $ var == 3 } { puts "var is equal to 3# } else { puts "var is different of 3# }

Tcl Tutorial

Oct-2000

- Slide 23 -

Control Structures - Conditional Cmd


switch: switch flags value pattern1 body1 pattern2 body2 ... switch -regexp -- $var { "hu. * # "foo. * # { puts "var starts with hu or with foo# } " . *bar# { puts "var ends with bar# } default { puts "var is $var# } }
Tcl Tutorial Oct-2000 - Slide 24 -

Control Structures - Loops


while loop: while test body
set i 0 while { $ i < 10 } { puts $i incr i } for { set i 0 } { $i < 10 } { incr i } { puts $i }

for loop: for start test next body

loop flow: break, continue break causes immediate exit from the loop while continue causes the loop to go over to the next iteration.
Tcl Tutorial Oct-2000 - Slide 25 -

Control Structures - Loops - foreach


simple foreach: foreach varname list body
foreach var { a b c d } { puts $var }

foreach loop: foreach varlist1 list1 ?varlist2 list2 . . . ? body


foreach { var value } { a 1 b 2 c 3 } { puts " $ var is $ value# }

Tcl Tutorial

Oct-2000

- Slide 26 -

Strings

Tcl Tutorial

Oct-2000

- Slide 27 -

Strings
String length: string length string
string length " Hi lsiVega# string index " Hi lsiVega# 4 ; # -> 10 ; # -> s

String indexing: string index string index String matching: string match pattern string

string match " Hi * # " Hi lsiVega# ; # -> 1 string tolower "Hi lsiVega# ; # -> hi lsivega

Lower/upper case: string tolower string ; string toupper string

Trim string: string trim string ?chars? ; string trimleft / trimright


string trim " Hi lsiVega# " agi#
Tcl Tutorial Oct-2000

; # -> Hi lsiVe

- Slide 28 -

Strings
String search: string first search-string string ; string last
string first "lsi# " Hi lsiVega# ; # -> 3

Sub-String extraction: string range string first last


string range " Hi lsiVega# 3 end

; # -> lsiVega

String comparing: string compare ?-nocase? string1 string2


string compare " Hi # " Hi lsiVega# ; # -> -1

Appending strings: append var-name value value ...


set var " Hi # append var " lsiVega#; puts $ var ; # -> HilsiVega

Tcl Tutorial

Oct-2000

- Slide 29 -

Strings
String formating: format format arg arg ...
format "-%20s %. 4f-# " abc# 1. 987654321 ; # -> abc 1. 9877-

Parsing strings: scan string format var var . . .

scan " abc 1. 9877 # " %s %f# var1 var2 ; # -> 2 puts $var1 ; # -> abc puts $var2 ; # -> 1. 9877

Tcl Tutorial

Oct-2000

- Slide 30 -

Lists
A Tcl list is a Tcl string with list elements separated by spaces. List elements are grouped like command arguments. List operations are fast in Tcl.

Tcl Tutorial

Oct-2000

- Slide 31 -

Lists
Building lists: list value value . . .
set x { d e} set l1 [ list a $ x " b c# ] ; # -> a { d e} { b c}

the list command does automatic quoting Appending elements to lists: lappend list value value . . .
lappend l1 g f ; # -> a { d e} { b c} g f

Indexing lists: lindex list index


lindex $l1 2

; # -> b c

Tcl Tutorial

Oct-2000

- Slide 32 -

Lists
Sorting lists: lsort -integer|-dictionary|... list
lsort $ l1 ; # -> a { b c} { d e} f g

Length of lists: llength list


llength $l1

; # -> 5

Searching in lists: lsearch -exact|-glob|-regexp list pattern


lsearch $l1 f ; # -> 3

Concatenate lists: concat list list . . .

concat $l1 f $l1 ; # -> a { d e} { b c} g f f a { d e} { b c} g f

Tcl Tutorial

Oct-2000

- Slide 33 -

Lists
Merge elements of a list: join list join-string
set a [ j oin $l1 / ] ; # -> a/d e/b c/g/f split $a / ; # -> a { d e} { b c} g f

Spliting list in elements: split list split-characters Extract sub-list: lrange list first last
lrange $l1 2 3

; # -> { b c} g

Replace elements: lreplace list first last element element . . .


lreplace $l1 2 3 q linsert $l1 2 w ; # -> a { d e} q f

Insert elements into list: linsert list index element element . . .


; # -> a { d e} w { b c} g f
Oct-2000

Tcl Tutorial

- Slide 34 -

Arrays
Variable with an string typed index
set my_array( my_index) " I $ m an array value # puts $my_array( my_index)

array <subcommand> array names arr ?pattern? returns index names matching pattern array get arr ?pattern? return index/value pairs array set arr key1 value1 key2 value2 . . . ? what does this? Multidimensional arrays
set field( $x, $y) $ value

Tcl Tutorial

Oct-2000

- Slide 35 -

Looping over arrays


Converting array into a list
set volt( best) 2. 75; set volt( nom) 2. 5; set volt( worst) 2. 25 foreach voltage [ array names volt ] { puts " $ voltage: $volt( $voltage) # } set volt( best) 2. 75; set volt( nom) 2. 5; set volt( worst) 2. 25 foreach { voltage value } [ array get volt ] { puts " $ voltage: $value # }
Tcl Tutorial Oct-2000

Converting array into a double-list

- Slide 36 -

Data structures using arrays


Records:
set name " Roland# set people( $ name, phone) " +39/039/6573736 # set people( $ name, group) " FDM# foreach key [ array names people( Roland, *) ] { puts " $ people( $ key) # }

Stacks List of arrays

Tcl Tutorial

Oct-2000

- Slide 37 -

Procedures
proc name arguments body
proc print { msg1 msg2 } { return " $msg1 $ msg2 # } print Hello Ciao ; # -> Hello Ciao

Default arguments

proc inc { var { value +1 } } { . . . } proc print { msg args } { puts " $ msg $args# } print Hi lsi vega 2000 ; # -> Hi lsi vega 2000
Oct-2000

Variable number of arguments

Tcl Tutorial

- Slide 38 -

Procedures
Create link to variable in a different stack frame upvar ?level? other-var myvar
proc sample { table_var } { upvar $ table_var table } puts [ array get table ]

array set ary a 1 b 2 c 3 sample ary

Tcl Tutorial

Oct-2000

- Slide 39 -

File -IO
file <sub-command> file mkdir creates a directory file exists checks whether or not a file/directory exists file rename renames a file/directory file dirname returns the parent directory of the given file name file delete deletes a file/directory file copy copies files many more . ..

Tcl Tutorial

Oct-2000

- Slide 40 -

File -IO
Open file: open filename ?mode? ?permissions?
set fileid [ open " . cshrc# " w# ] ; # opens file set fileid [ open " | sort . cshrc# " r# ] ; # opens pipe

Close file: close fileid


close $fileid

Read from file: gets fileid varname ; read ?-nonewline? fileid


while { [ gets $fileid line ] >= 0 } { . . . } set data [ read $ fileid ]

Write to file: puts ?-nonewline? ?fileid? string


puts $fileid "Hi lsiVega#

Tcl Tutorial

Oct-2000

- Slide 41 -

Wildcards (glob)
Globbing is used for simple string (string match, lsearch, switch) and file (glob) matching.
? * [chars] {a, b, . . . } Matches any single character Matches any sequence of zero or more characters. Matches any single character in chars. If chars contains a sequence of the form a-b then any character between a and b (inclusive) will match. Matches any of the strings a, b, etc.

Tcl wildcards are similar to sh/csh wildcards


but no sorting csh doesn $ t check for existence unless the pattern contains ?, * or [ ] (try echo aaa versus echo aaa*)

Tcl Tutorial

Oct-2000

- Slide 42 -

Regular expressions
Regular expressions are used for more sophisticated string matching. New advanced regular expressions in Tcl 8.1 .

Tcl Tutorial

Oct-2000

- Slide 43 -

Regular expressions - Patterns


Pattern basics
. [chars] * ? + ^ $ () | \ Matches any single character Matches any single character in chars. Supports range of characters [a-b]. Supports negation of character set [^. . . ] Matches 0 or more of the previous pattern. Matches 0 or 1 of the previous pattern. Matches 1 or more of the previous pattern. Matches only at the start of a string. Matches only at the end of a string. Groups pattern. Matches just one alternative (or). Escapes special characters.
Tcl Tutorial Oct-2000

- Slide 44 -

Regular expressions - regexp


regexp ?switches? pattern string ?match-var? ?sub-match-var?... compares a string to a regular expression returns 1 of the expression matches, otherwise it returns 0 it stores the matched part of the string in match-var it stores subparts of the matched string in sub-match-var switches -nocase, -all or many others (see man-page) Example: set display muncs18: 0. 1 regexp { ( [ ^: ] *) : [ 0-9] +} $display match submatch1 ; # -> 1 puts $match ; # muncs18: 0 puts $submatch1 ; # muncs18

Tcl Tutorial

Oct-2000

- Slide 45 -

Regular expressions - regsub


regsub ?switches? pattern string substitute-expression var substitutes matching parts of a string with a substitute-expression returns the number of replaced strings it stores the new string in var switches -nocase, -all or many others (see man-page) & (or \0) will be replace with the portion of the string which matches pattern \1 . . . \9 will be replaced with the portion of the string which matches the 1 st . . 9th group Example: set display muncs18: 0. 1 regsub { ( [ ^: ] *: ) [ 0-9] +} $display { \14} var puts $var ; # muncs18: 4. 1

; # -> 1

Tcl Tutorial

Oct-2000

- Slide 46 -

Advanced regular expressions


non-greedy matching * and + make regexps matching as much text as possible adding a ? after the qualifier makes them matching the least text they can
set line { " a# " b# " c# } regexp { " . * # } $ line var; puts $ var ; # -> " a# " b# " c# regexp { " . *? # } $line var; puts $var ; # -> " a#

backslash escapes are now interpreted by the regexp engine itself regexp { [ a-z] \n} instead of regexp " \[ a-z\] \n#

Tcl Tutorial

Oct-2000

- Slide 47 -

Advanced regular expressions


back-references matches the same string that was matched by a previous group regexp { ^( . *) \1$ } $ line ; # matches double words sep. with space constraint escapes constraints an regexp to match only at a certain place \m matches only at the start of a word internationalization character classes [[:digit:]] or \d matches one digit [[:alpha:]] matches one letter but includes also special language characters (german , spanish and many more [a-z] does not cover)
Tcl Tutorial Oct-2000

- Slide 48 -

Advanced regular expressions


Bounds new quantifiers allow to specify how many time the previous part must be repeated in order to match (extension of ?, * and +) {m} allows exactly m repetitions {m,} allows m or more repetitions {m,n} allows at least m but not more than n repetitions

Tcl Tutorial

Oct-2000

- Slide 49 -

Error handling
Generating an error: error message error " $opt is not a legal option# Trap errors: catch tcl-commands ?var?
if { [ catch { open $filename " r# } msg ] } { puts " Can not open file & $ filename$ , got & $ msg$ . # }

Getting stack trace after an error: puts $errorInfo

Tcl Tutorial

Oct-2000

- Slide 50 -

Different stuff
Load a Tcl script source filename Exit the Tcl shell exit Get the history of commands typed history Get information about Tcl internals info option Make a system call exec args Evaluate a string as a Tcl command eval args Perform backslash, command, and variable substitutions subst Change directory cd Get working directory pwd

Tcl Tutorial

Oct-2000

- Slide 51 -

Advanced Concepts
namespace socket uplevel/upvar multiple interpreters/safe interpreters binary file handling threads

Tcl Tutorial

Oct-2000

- Slide 52 -

TCL-Reference

http: //dev. scriptics. com/man/

Tcl Tutorial

Oct-2000

- Slide 53 -

Tcl & EDA Market


Synopsys Formality, Primetime, newer Design Compiler Ambit Buildgates Mentor Modelsim LSI lsivega and many other EDA tools and it expands fast

It may be useful to have a basic understanding of Tcl!!


Tcl Tutorial Oct-2000 - Slide 54 -

Вам также может понравиться