Upload
parthjadeja2001
View
86
Download
2
Embed Size (px)
Citation preview
Tcl Tcl TutorialTutorial
Tcl Tutorial Oct-2000
- Slide 2 -
OutlineOutline
q Tcl Tutorial
q Outline
q What is Tcl ?
q What is Tk ?
q Why is Tcl that successful ?
q When using Tcl ?
q Why is Tcl better than ...?
q Tcl Extensions
q Getting started
q Example !Compute factorial
q Tcl Fundamentals
q Tcl Basics
q Comments
q Mathematical Expressions
q Control Structures
q Strings
q Lists
q Arrays
q Procedures
q File-IO
q Wildcards (glob)
q Regular expressions
q Error handling
q Different stuff
q Advanced Concepts
q TCL-Reference
q Tcl & EDA Market
Tcl Tutorial Oct-2000
- Slide 3 -
What is What is TclTcl ??
q Tool Command Language ( tickle )" #
q Scripting language
n simple syntax
q Library package
n can be embedded in applications
n language parser
n build in commands
n extensible
Tcl Tutorial Oct-2000
- Slide 4 -
What is What is TkTk ??
q Graphical user interface toolkit.
q Tk is portable.
q Tk is easy to use.
q Tk allows rapid development.
q Tk implements platform look and feel on UNIX, Windows and Mac.
q lsivega graphical user interface is 1 00% Tk.
Tcl Tutorial Oct-2000
- Slide 5 -
Why is Tcl that successful ?Why is Tcl that successful ?
q Tcl provides programmability.
q Tcl application needs to implement only application specific low level commands.
q Tcl is a Vendor independent standard.
q Tcl is easy to learn.
q Tcl is a complete language.
q Tcl is complete royalties free.
q Tcl and Tk are highly portable.
q Tcl supports rapid development.
q Tcl makes your application extensible.
Tcl Tutorial Oct-2000
- Slide 6 -
When using When using TclTcl ??
q 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 7 -
Why is Tcl better than . . .?Why is Tcl better than . . .?
F e a tu re s (w w w . s c r i p t i c s . c om ) T c l P e r l P y th o n J a v a S c r i p t
V i s u a l B a s i c
Ra p i d d e ve l o pm e n t ü ü � ü � ü � ü �
F l e x i b l e , ra p i d e v o l u t i o n
ü � ü � ü � ü � ü �
I n te ra c t i v e S h e l l ü �
S p e e d o f u s e
G re a t re g u l a 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 ü � ü � ü
Em b e d d a b l e ü � ü �
E a s y G U I s ü � ( Tk ) ( T k) ü �
B re a d th o f fu n c t io n a l i ty
I n te rn e t re a d y ü � ü � ü � ü � ü �
C ro s s p l a tfo rm ü � ü � ü � ü �
Th re 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 r i e n te d ü ( iT c l ) ü � ü � ü � ü �
E n te rp r i s e u s a g e
M a in ta i n a b i l i ty ü ü � ü � ü �
�
�
Tcl Tutorial Oct-2000
- Slide 8 -
Tcl ExtensionsTcl Extensions
q Graphical user interface
q Object system
q Automating interactive applications
q Networking
q Database access
Tcl Tutorial Oct-2000
- Slide 9 -
Getting startedGetting started
q How to make run-able Tcl scripts:
n Create a text fi le which starts with#!<path to>/tclsh or if Tk is needed #!<path to>/wish
n 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 $@" #
n Make your script executable (chmod)
n Or source your script in a tclsh/wishtclshsource my_script. tcl
Tcl Tutorial Oct-2000
- Slide 1 0 -
Example Example !! Compute factorialCompute 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 1 -
Tcl FundamentalsTcl Fundamentals
q String based language - Everything is a string !
q Only a few constructs.
q Simple syntax.
q Tcl is interpreted.
q Tcl knows only two language constructs:
n commands
n variables
Tcl Tutorial Oct-2000
- Slide 1 2 -
q The concept of Tcl is a l ittle different than other languages
it s worth to understand the basic concepts !$
q Variables
q Commands
q Grouping
q Substitution
q Command call
Tcl BasicsTcl Basics
Tcl Tutorial Oct-2000
- Slide 1 3 -
Tcl Basics Tcl Basics -- VariablesVariables
q Set command is used to assign a valueset variable 2000
q The dollar sign $ is used to obtain the value from a variable.puts $var
q Case is significant for variable names.
q Variable names can contain any character and be of any length.
q Variables defined outside any procedure are global variables.
q Global variables are not automatically visible inside procedures.-> use global variable-name to make them accessible
q Variables don t need to be declared.$
Tcl Tutorial Oct-2000
- Slide 1 4 -
Tcl Basics Tcl Basics -- CommandsCommands
q A Tcl script is a sequence of commands.
q Basic syntax for a Tcl command:command-name arg1 arg2 arg3 . . .
q White spaces (space or tabs) separate command name and arguments.
q Newline or semicolon terminates a command.
q A command returns one string.
Tcl Tutorial Oct-2000
- Slide 1 5 -
Tcl Basics Tcl Basics -- GroupingGrouping
q Curly braces { } prevent substitution.
q Double quotes " # allow substitution.
q \ escapes white spaces (space, tabs, newlines).
q Braces { } and quotes " # are not part of the value.
Tcl Tutorial Oct-2000
- Slide 1 6 -
Tcl Basics Tcl Basics -- SubstitutionSubstitution
q Backslash substitution \
n Quotes special characters l iterally.
n Specify hexadecimal or octal values.
q Variable substitution $
n Substitute variable by value.puts $varset a \$bc; puts $a ; # -> $bc
q Command substitution [ ]
n Nesting commands.puts [ string length Hi " lsiVega# ]
Tcl Tutorial Oct-2000
- Slide 1 7 -
Tcl Basics Tcl Basics -- ExecutionExecution
q Execution calls the command passing all arguments.
q Command returns a value or an error.
Tcl Tutorial Oct-2000
- Slide 1 8 -
Example Example !! Compute factorialCompute 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 9 -
CommentsComments
q Comments in Tcl starts with the hash character #.
q The hash character must occur at the beginning of a command.
q The semicolon ; can be used to terminate the previous command.
set a 1 ; # I m a comment$
q Comments can be continued to the next l ine escaping the newline
# I m a long $ \comment
Tcl Tutorial Oct-2000
- Slide 20 -
Mathematical ExpressionsMathematical Expressions
q Evaluation of a mathematical expressionexpr arg arg . . .
q All arguments are concatenated together and evaluated as a Tcl expression.
q Expressions are subject of two rounds of substitutions!
n one by the Tcl interpreter
n one by expr itself
protect expressions with curly braces
Tcl Tutorial Oct-2000
- Slide 21 -
Mathematical ExpressionsMathematical Expressions
q Works with boolean, integer, double and strings.
q + - * / % ~ & | ^ ! && | | << >> < > <= >= == != ?:
q sin cos tan abs log sqrt ...
q Examplesexpr { 5 / 4 } ; # -> 1expr { 5 / 4. 0 } ; # -> 1. 25expr { 5 / ( 4 + 0. 0 ) } ; # -> 1. 25expr { a == g } ; # " # " # -> 0expr { a == g } ; # -> syntax errorexpr { asin(1) * 2 } ; # -> 3. 14159265359
Tcl Tutorial Oct-2000
- Slide 22 -
Control StructuresControl Structures
q Conditional commands
n if then else
n switch
q Loops
n while
n for
n foreach
n break, continue
q Others
n return, error, catch
Tcl Tutorial Oct-2000
- Slide 23 -
Control Structures Control Structures -- Conditional Conditional CmdCmd
q 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 24 -
Control Structures Control Structures -- Conditional Conditional CmdCmd
q 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 25 -
Control Structures Control Structures -- LoopsLoops
q while loop: while test bodyset i 0while { $i < 10 } {
puts $iincr i
}
q for loop: for start test next bodyfor { set i 0 } { $i < 10 } { incr i } {
puts $i}
q loop flow: break, continuebreak causes immediate exit from the loop while continue causes the loop to go over to the next iteration.
Tcl Tutorial Oct-2000
- Slide 26 -
Control Structures Control Structures -- Loops Loops -- foreachforeach
q simple foreach: foreach varname list body
foreach var { a b c d } {puts $var
}
q 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 27 -
StringsStrings
q
Tcl Tutorial Oct-2000
- Slide 28 -
StringsStrings
q String length: string length stringstring length Hi " lsiVega# ; # -> 10
q String indexing: string index string indexstring index Hi " lsiVega# 4 ; # -> s
q String matching: string match pattern stringstring match Hi * Hi " # " lsiVega# ; # -> 1
q Lower/upper case: string tolower string ; string toupper stringstring tolower "Hi lsiVega# ; # -> hi lsivega
q Trim string: string trim string ?chars? ; string trimleft / trimrightstring trim Hi " lsiVega# " agi# ; # -> Hi lsiVe
Tcl Tutorial Oct-2000
- Slide 29 -
StringsStrings
q String search: string first search-string string ; string last
string first "lsi# " Hi lsiVega# ; # -> 3
q Sub-String extraction: string range string first laststring range Hi " lsiVega# 3 end ; # -> lsiVega
q String comparing: string compare ?-nocase? string1 string2
string compare Hi Hi" # " lsiVega# ; # -> -1
q Appending strings: append var-name value value ...
set var " #Hiappend var "lsiVega#; puts $var ; # -> HilsiVega
Tcl Tutorial Oct-2000
- Slide 30 -
StringsStrings
q String formating: format format arg arg ...
format "-%20s %. 4f-# " abc# 1. 987654321
; # -> - abc 1. 9877-
q Parsing strings: scan string format var var . . .
scan "abc 1. 9877 %s %f var1 var2 ; # # " # -> 2puts $var1 ; # -> abcputs $var2 ; # -> 1. 9877
Tcl Tutorial Oct-2000
- Slide 31 -
ListsLists
q A Tcl l ist is a Tcl string with l ist elements separated by spaces.
q List elements are grouped like command arguments.
q List operations are fast in Tcl.
Tcl Tutorial Oct-2000
- Slide 32 -
ListsLists
q Building lists: list value value . . .set x { d e}set l1 [ list a $x b c ]" # ; # -> a { d e} { b c}
n the l ist command does automatic quoting
q Appending elements to l ists: lappend list value value . . .lappend l1 g f ; # -> a { d e} { b c} g f
q Indexing lists: lindex list indexlindex $l1 2 ; # -> b c
Tcl Tutorial Oct-2000
- Slide 33 -
ListsLists
q Sorting lists: lsort -integer|-dictionary|... listlsort $l1 ; # -> a { b c} { d e} f g
q Length of l ists: llength listllength $l1 ; # -> 5
q Searching in l ists: lsearch -exact|-glob|-regexp list patternlsearch $l1 f ; # -> 3
q 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 34 -
ListsLists
q Merge elements of a l ist: join list join-stringset a [ join $l1 / ] ; # -> a/d e/b c/g/f
q Spliting list in elements: split list split-characterssplit $a / ; # -> a { d e} { b c} g f
q Extract sub-list: lrange list first lastlrange $l1 2 3 ; # -> { b c} g
q Replace elements: lreplace list first last element element . . .lreplace $l1 2 3 q ; # -> a { d e} q f
q Insert elements into l ist: linsert list index element element . . .linsert $l1 2 w ; # -> a { d e} w { b c} g f
Tcl Tutorial Oct-2000
- Slide 35 -
ArraysArrays
q Variable with an string typed indexset my_array(my_index) I m an array value" $ #
puts $my_array(my_index)
q array <subcommand>
n array names arr ?pattern? returns index names matching pattern
n array get arr ?pattern? return index/value pairs
n array set arr key1 value1 key2 value2 . . . ? what does this?
q Multidimensional arraysset field($x, $y) $value
Tcl Tutorial Oct-2000
- Slide 36 -
Looping over arraysLooping over arrays
q Converting array into a l istset volt(best) 2. 75;set volt(nom) 2. 5;set volt(worst) 2. 25foreach voltage [ array names volt ] {
puts $voltage: $volt($voltage)" #
}
q Converting array into a double-listset volt(best) 2. 75;set volt(nom) 2. 5;set volt(worst) 2. 25foreach { voltage value } [ array get volt ] {
puts $voltage: $value" #
}
Tcl Tutorial Oct-2000
- Slide 37 -
Data structures using arraysData structures using arrays
q 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)" #
}
q Stacks
q List of arrays
Tcl Tutorial Oct-2000
- Slide 38 -
ProceduresProcedures
q proc name arguments bodyproc print { msg1 msg2 } {
return $msg1 $msg2" #
}
print Hello Ciao ; # -> Hello Ciao
q Default argumentsproc inc { var { value +1 } } { . . . }
q Variable number of argumentsproc print { msg args } { puts $" msg $args# }
print Hi lsi vega 2000 ; # -> Hi lsi vega 2000
Tcl Tutorial Oct-2000
- Slide 39 -
ProceduresProcedures
q Create link to variable in a different stack frameupvar ?level? other-var myvar
proc sample { table_var } {upvar $table_var table
puts [ array get table ]}
array set ary a 1 b 2 c 3sample ary
Tcl Tutorial Oct-2000
- Slide 40 -
FileFile--IOIO
q file <sub-command>
n fi le mkdir creates a d irectory
n fi le exists checks whether or not a fi le/directory exists
n fi le rename renames a fi le/directory
n fi le d irname returns the parent d irectory of the given fi le name
n fi le delete deletes a fi le/directory
n fi le copy copies fi les
n many more . . .
Tcl Tutorial Oct-2000
- Slide 41 -
FileFile--IOIO
q Open file: open filename ?mode? ?permissions?set fileid [ open ." cshrc# " # w ] ; # opens fileset fileid [ open | sort ." cshrc# " # r ] ; # opens pipe
q Close file: close fileidclose $fileid
q Read from file: gets fileid varname ; read ?-nonewline? fileidwhile { [ gets $fileid line ] >= 0 } { . . . }set data [ read $fileid ]
q Write to file: puts ?-nonewline? ?fileid? stringputs $fileid "Hi lsiVega#
Tcl Tutorial Oct-2000
- Slide 42 -
Wildcards (glob)Wildcards (glob)
q Globbing is used for simple string (string match, lsearch, switch) and file (glob) matching.
n ? Matches any single character
n * Matches any sequence of zero or more characters.
n [chars] Matches any single character in chars. I f charscontains a sequence of the form a-b then any characterbetween a and b (inclusive) wil l match.
n {a,b, . . . } Matches any of the strings a, b, etc.
q Tcl wildcards are similar to sh/csh wildcards
n but no sorting
n csh doesn t check for existence unless the pattern contains ?, * or $ [ ] (try echo aaa versus echo aaa*)
Tcl Tutorial Oct-2000
- Slide 43 -
Regular expressionsRegular expressions
q Regular expressions are used for more sophisticated string matching.
q New advanced regular expressions in Tcl 8.1 .
Tcl Tutorial Oct-2000
- Slide 44 -
Regular expressions Regular expressions -- PatternsPatterns
q Pattern basicsn . Matches any single character
n [chars] Matches any single character in chars.Supports range of characters [a-b] .Supports negation of character set [^. . . ]
n * Matches 0 or more of the previous pattern.
n ? Matches 0 or 1 of the previous pattern.
n + Matches 1 or more of the previous pattern.
n ^ Matches only at the start of a string.
n $ Matches only at the end of a string.
n () Groups pattern.
n | Matches just one alternative (or).
n \ Escapes special characters.
Tcl Tutorial Oct-2000
- Slide 45 -
Regular expressions Regular expressions -- regexpregexp
q regexp ?switches? pattern string ?match-var? ?sub-match-var?...
n compares a string to a regular expression
n returns 1 of the expression matches, otherwise it returns 0
n it stores the matched part of the string in match-var
n it stores subparts of the matched string in sub-match-var
n switches -nocase, -all or many others (see man-page)
q Example:set display muncs18: 0. 1regexp { ([^: ] *) : [0-9] +} $display match submatch1 ; # -> 1puts $match ; # muncs18: 0puts $submatch1 ; # muncs18
Tcl Tutorial Oct-2000
- Slide 46 -
Regular expressions Regular expressions -- regsubregsub
q regsub ?switches? pattern string substitute-expression var
n substitutes matching parts of a string with a substitute-expression
n returns the number of replaced strings
n it stores the new string in var
n switches -nocase, -all or many others (see man-page)
n & (or \0) wil l be replace with the portion of the string which matches pattern
n \1 . . . \9 wil l be replaced with the portion of the string which matches the 1 st . . 9th group
q Example:set display muncs18: 0. 1regsub { ([^: ] *: ) [0-9] +} $display { \14} var ; # -> 1puts $var ; # muncs18: 4. 1
Tcl Tutorial Oct-2000
- Slide 47 -
Advanced regular expressionsAdvanced regular expressions
q non-greedy matching
n * and + make regexps matching as much text as possible
n adding a ? after the qualifier makes them matching the least text they canset line { a b c }" # " # " #
regexp { . * } $line " # var; puts $var ; # -> a b c" # " # " #
regexp { . *? } $line" # var; puts $var ; # -> a" #
q backslash escapes
n are now interpreted by the regexp engine itselfregexp { [a-z] \n} instead of regexp "\[a-z\] \n#
Tcl Tutorial Oct-2000
- Slide 48 -
Advanced regular expressionsAdvanced regular expressions
q back-references
n matches the same string that was matched by a previous groupregexp { ^(. *) \1$} $line
; # matches double words sep. with space
q constraint escapes
n constraints an regexp to match only at a certain place\m matches only at the start of a word
q internationalization
n character classes[[:digit: ]] or \d matches one d igit[[:alpha: ]] matches one letter but includes also special languagecharacters (german ä, spanish ñ and many more [a-z] does notcover)
Tcl Tutorial Oct-2000
- Slide 49 -
Advanced regular expressionsAdvanced regular expressions
q Bounds
n new quantifiers allow to specify how many time the previous partmust 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 50 -
Error handlingError handling
q Generating an error: error message
error $opt is not a legal option" #
q Trap errors: catch tcl-commands ?var?
if { [ catch { open $filename r } " # msg ] } {puts Can not open file $filename , got $" & $ & msg$ . #
}
q Getting stack trace after an error: puts $errorInfo
Tcl Tutorial Oct-2000
- Slide 51 -
Different stuffDifferent stuff
q Load a Tcl script source filename
q Exit the Tcl shell exit
q Get the history of commands typed history
q Get information about Tcl internals info option
q Make a system call exec args
q Evaluate a string as a Tcl command eval args
q Perform backslash, command, and variable substitutions subst
q Change directory cd
q Get working directory pwd
Tcl Tutorial Oct-2000
- Slide 52 -
Advanced ConceptsAdvanced Concepts
q namespace
q socket
q uplevel/upvar
q multiple interpreters/safe interpreters
q binary file handling
q threads
Tcl Tutorial Oct-2000
- Slide 53 -
TCLTCL--ReferenceReference
http: //dev. scriptics. com/man/
Tcl Tutorial Oct-2000
- Slide 54 -
Tcl & EDA MarketTcl & EDA Market
q Synopsys Formality, Primetime, newer Design Compiler
q Ambit Buildgates
q Mentor Modelsim
q LSI lsivega
q and many other EDA tools and it expands fast
q It may be useful to have a basic understanding of Tcl! !