Top Banner
What is TCL? Tool Command Language An interpreted programming language Created by John Ousterhout. Intended to be embedded with application. But used in rapid prototyping, scripting, GUI, testing of SW. • Platform-independent All operations are commands, including language structures. Everything can be dynamically redefined and overridden. All data types can be manipulated as strings. Need little experience with programming – Easy Programs are short, efficient
30

TCL Tutorial

Nov 08, 2014

Download

Documents

Ahmed Sayed

Introduction to TCL scripting language
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: TCL Tutorial

What is TCL?

• Tool Command Language • An interpreted programming language

• Created by John Ousterhout. • Intended to be embedded with application. • But used in rapid prototyping, scripting, GUI, testing of SW.

• Platform-independent• All operations are commands, including language

structures.• Everything can be dynamically redefined and overridden. • All data types can be manipulated as strings. • Need little experience with programming

– Easy– Programs are short, efficient

Page 2: TCL Tutorial

Let’s Code

• Hello world– puts "Hello, world!“

• How to run program?– Tclsh – interactive mode– Tclsh prog.tcl– Double click .tcl file

Page 3: TCL Tutorial

Constants• In Tcl, all free constants are strings

– abc is the same as “abc”– “5” is the same as 5

• <, >, == ,<= and >= compare numerically– If any of the arguments are non-numbers, errors are

thrown• Strings can also be compared literally:

– string compare string1 string2

Page 4: TCL Tutorial

Variable

• A Tcl variable is a C-style name, which satisfies the regular expression:– {[A-Za-z_][A-Za-z_0-9]*}

• Examples:– iterator– loopInit– _ErrorCount76

• Non-examples:– 78Cool– ~notAVariable

Page 5: TCL Tutorial

Variables (cont..)

• “set” command– Usage: set <varname> <value>

• Example:– set a 5– puts $a (puts = putString – exactly like C’s)

– Will print out 5

Page 6: TCL Tutorial

How TCL works

• Handling Commands– Argument Processing

• Grouping– White spaces– “” vs {}

• Substitution– Variable substitution $varName– Command substitution [aCommand arg1 arg2 …]

– Command Execution

Page 7: TCL Tutorial

Example 1

command1 abc 123 xyz 456

command2 {abc 123} xyz 456

command3 abc “123 $xyz” 456

command4 abc 123 [anotherCommand xyz 456]

Page 8: TCL Tutorial

Example 2

proc PrintList {aList} {

foreach anItem $aList {

puts $anItem

}

}

set ITEM1 item1

Set ITEM2A item2a

PrintList “item0 $ITEM1 {$ITEM2A item2b}”

Page 9: TCL Tutorial

TCL vs Other shells

• Grouping precedes substitution in TCL only

csh> setenv GARGS “-i word file.txt”

csh> grep $GARGS

tclsh% set ARGS {ab aabb m}

tclsh% regexp $ARGS

wrong # args: should be "regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?"

Page 10: TCL Tutorial

Basic operations

• print to screen (puts)– puts –nonewline "Hello, world!"– puts "!!"

• assignment (set)– set income 32000– puts "income is $income"

• mathematical expressions (expr)– set a 10.0– expr $a + 5 – expr int($a/3)

Page 11: TCL Tutorial

Some useful commands

• unset: destroy a variable– unset num

• info: check whether the named variable has been defined– if {![info exists num]} {

set num 0}incr num

• Comments• # : single-line comments, similar to "//" in C• ;# : in-line comments, just like "//" in C

Page 12: TCL Tutorial

User Input

• Command line –– argc – no of command line arguments– argv0 – program name– argv – list of command line arguments

• User input –– set userName [gets stdin]– gets stdin inlinevar

Page 13: TCL Tutorial

Operators

• Unary (- + ~ !) : – Unary minus, unary plus, bit-wise NOT, logical NOT

• + - * / % : – Add, Subtract, Multiply, divide, remainder

• ** : – Exponentiation

• << >> : – Left and right (bit) shift

• Comparison operators– Numbers : < > <= >= – String : eq ne in ni (string compare str1 str2)

• Bitwise (& | ^ ~):– Bitwise and, or, exclusive or, not

• Logical (&& || !):– Logical and, or, not

Page 14: TCL Tutorial

Control structures (1)• if then else set income 32000 if {$income > 30000} {

puts "$income -- high"

} elseif {$income > 20000} {

puts "$income -- middle"

} else {

puts "$income -- low"

}

• while loops set i 0 while {$i < 100} {

puts "I am at count $i"

incr i

}

Page 15: TCL Tutorial

Control structures (2)• for loops for {set i 0} {$i < 100} {incr i} { puts "I am at count $i and going up"

}

for {set i 100} {$i > 0} {incr i -1} {

puts "I am at count $i and going down"

}

• foreach loops set lstColors {red orange yellow green blue purple} foreach c $lstColors {

puts $c

}

Page 16: TCL Tutorial

Control structures (3)• foreach loops (con't)

set lstColors {red orange yellow green blue purple} foreach {a b c} $lstColors { puts "$c--$b--$a" }

set lstFoods {apple orange banana lime berry grape} foreach f $lstFoods c $lstColors { puts "a $f is usually $c" }

foreach {a b} $lstFoods c $lstColors { puts "$a & $b are foods. $c is a color." }

Page 17: TCL Tutorial

Procedures• procedure calls (embedded commands)

set b [expr $a + 5]

puts "The value of b is $b"

• create your own procedure (called by value only)proc foo {a b c} {

return [expr $a * $b - $c]

}

puts [expr [foo 2 3 4] + 5]

proc bar { } {

puts "I'm in the bar procedure"

}

bar

Page 18: TCL Tutorial

Procedures (default value)

• Optional Parameters are very easy to set up in Tcl• By Example:

proc Add { number {by 1} } {return [expr $number+$by]

}

• The variable by takes on a default of 1 unless specified otherwise in the function callAdd 1 ;# Will return 2Add 1 2 ;# Will return 3Add 1 –1 ;# Will return 0

Page 19: TCL Tutorial

Variable scope• local and global variablesset a 5set b 6set c 7proc var_scope { } { global a set a 3 set b 2 set ::c 1}var_scopeputs "The value for a b c is: $a $b $c"

Page 20: TCL Tutorial

Procedures (variable args)

• Variable length arguments supported by args keyword which can be placed at the end of argument listproc sum args {

set s 0foreach i $args {

incr s $i}return $s

}

– sum 1 2 3 4 5

Page 21: TCL Tutorial

List

• Many ways to create a list set myList [list a b c]

set myList "a b c"

set myList {a b c}

set lst [split "item 1.item 2.item 3" "."] • Retrieving an element within a list: lindex• lindex is 0-based, just like C

set b [lindex $a 3]

set b [lindex $a end]

Page 22: TCL Tutorial

List operations• llength : Return the length of a list

– llength [list 1 2 3] will be 3– llength [list] will be 0

• concat : Concatenate two lists– set b [concat [list 1 2 3 4] [list 5 6 7]]– b will be { 1 2 3 4 5 6 7 }

• lappend : Append value at the end of list – By Name– set a [list 1 2 3]– lappend a 4– Now a will be { 1 2 3 4 }– Note: lappend takes a list Name, not a list

• linsert list index arg1 ?arg2 ... argn? – Returns a new list with the new list elements inserted just before the index th element of

listName (set b [linsert $a 3 "1 2 3"] )

• lreplace list first last ?arg1 ... argn? – Returns a new list with N elements of listName replaced by the args (set b [lreplace $b 3 5 "AA"

"BB"] )

• lset varName index newValue – The lset command can be used to set elements of a list directly, instead of using lreplace

Page 23: TCL Tutorial

List operations

• lsearch list pattern – Searches list for an entry that matches pattern, and returns the index for the first

match, or a -1 if there is no match. By default, lsearch uses "glob" patterns for matching.

• lsort list – Sorts list and returns a new list in the sorted order.

• lrange list first last – Returns a list composed of the first through last entries in the list.

Page 24: TCL Tutorial

String subcommands (1)

• string match (uses glob patterns)– # Matches string match f* foo – # Matches string match f?? foo – # Doesn't match string match f foo

• string length string – Returns the length of string.

• string index string index – Returns the indexth character from string.

• string range string first last – Returns a string composed of the characters from first to last.

Page 25: TCL Tutorial

String subcommands (2)• string compare string1 string2

– Compares string1 to string2 and returns: – -1 ..... If string1 is less than string2 – 0 ........ If string1 is equal to string2 – 1 ........ If string1 is greater than string2

• string first string1 string2 – Returns the index of the character in string1 that starts the first match to string2,

or -1 if there is no match. (set first [string first "/" $path]; returns index of first / in $path )

• string last string1 string2 – Returns the index of the character in string1 that starts the last match to string2, or -1 if

there is no match.

• string wordend string index – Returns the index of the character just after the last one in the word which contains the

index'th character of string. A word is any contiguous set of letters, numbers or underscore characters, or a single other character.

• string wordstart string index – Returns the index of the character just before the first one in the word which contains the

index'th character of string.

Page 26: TCL Tutorial

String subcommands (3)• string tolower string

– Returns string with all the letters converted from upper to lower case. • string toupper string

– Returns string with all the letters converted from lower to upper case. • string trim string ?trimChars?

– Returns string with all occurrences of trimChars removed from both ends. By default trimChars are whitespace (spaces, tabs, newlines). Note that the characters are not treated as a "block" of characters - in other words, string trim "davidw" dw would return the string avi and not davi.

• string trimleft string ?trimChars? – Returns string with all occurrences of trimChars removed from the left. By default

trimChars are whitespace (spaces, tabs, newlines) • string trimright string ?trimChars?

– Returns string with all occurrences of trimChars removed from the right. By default trimChars are whitespace (spaces, tabs, newlines)

• format formatString ?arg1 arg2 ... argN? – (printf in C) set price4 [format "%-20s %10.2f per Lb." Steak 3.59997]

Page 27: TCL Tutorial

Array operationsAssociative arrays (string as index)set color(rose) redset color(sky) blueset color(medal) goldputs [array exists color]

(tests if an array with the name "color" exists)puts [array names color] (returns a list of the keys)foreach item [array names color] { puts "$item is $color($item)"} (iterating through array)set lstColor [array get color] (convert array to list)array set color $lstColor (convert list to array)

• array size arrayName – Returns the number of elements in array arrayName

• array unset arrayName ?pattern? – Unsets all of the elements in the array. If

pattern exists, only the elements that match pattern are unset.

Page 28: TCL Tutorial

File Handling• The simplest methods to access a file are via gets and puts. • Sometimes more efficient to use the read command to load an entire file,

and then parse the file into lines with the split command. • open fileName ?access?

– access can be r, r+, w, w+, a, a+

set fRead [open source.txt r]set fWrite [open target.txt w]while {![eof $fRead]} { set strLine [gets $fRead] ;#or gets $fRead strLine regsub –nocase –all "fan" $strLine "kristy" strLine puts $fWrite $strLine}close $fReadclose $fWrite

Page 29: TCL Tutorial

File Handling (cont..)• read ?-nonewline? fileID

– Reads all the remaining bytes from fileID, and returns that string. If -nonewline is set, then the last character will be discarded if it is a newline. Any existing end of file condition is cleared before the read command is executed.

• read fileID numBytes – Reads up to numBytes from fileID, and returns the input as a Tcl string.

• seek fileID offset ?origin? – Change the current position within the file referenced by fileID. Origin can be

start, current, end• tell fileID

– Returns the position of the access pointer in fileID as a decimal string.

• Count the no of line in file• # gets with two arguments returns the length of the line, • # -1 if the end of the file is found

• while { [gets $infile line] >= 0 } { incr number } close $infile

Page 30: TCL Tutorial

More

• TCL Guide

• www.ActiveState.com