You are on page 1of 52

Tcl Commands

Quick Reference

1
Surya Gadde

Table of Contents
Simple Text output (puts command) ........................................................................................................ 6
Assigning values to variables (set command) ........................................................................................... 6
Evaluations and Substitutions ................................................................................................................... 6
Using “ “ (Quotes) ................................................................................................................................. 6
Using {} (braces) .................................................................................................................................... 7
Using [ ] (Brackets) ................................................................................................................................ 7
Math functions .......................................................................................................................................... 8
Switch command....................................................................................................................................... 9
If command ............................................................................................................................................. 10
A simple ‘if’ command ........................................................................................................................ 10
If..else command................................................................................................................................. 10
If …elseif….else command ................................................................................................................... 10
While Loop .............................................................................................................................................. 10
For loop ................................................................................................................................................... 11
Procedures .............................................................................................................................................. 11
Global ...................................................................................................................................................... 12
Upvar ....................................................................................................................................................... 13
List ........................................................................................................................................................... 15
lindex ................................................................................................................................................... 15
llength ................................................................................................................................................. 15
lappend ............................................................................................................................................... 16
linsert .................................................................................................................................................. 16
lreplace................................................................................................................................................ 16
lsearch ................................................................................................................................................. 17
lsort ..................................................................................................................................................... 17
lrange .................................................................................................................................................. 18
concat.................................................................................................................................................. 18
String command ...................................................................................................................................... 19
string length ........................................................................................................................................ 19

2

string index.......................................................................................................................................... 19
string range ......................................................................................................................................... 19
string compare .................................................................................................................................... 19
string first ............................................................................................................................................ 20
string last ............................................................................................................................................. 20
string wordstart .................................................................................................................................. 21
string wordend .................................................................................................................................... 21
string match ........................................................................................................................................ 21
string tolower ...................................................................................................................................... 22
string toupper ..................................................................................................................................... 22
string totitle ........................................................................................................................................ 22
string trim............................................................................................................................................ 22
string trimleft ...................................................................................................................................... 22
string trimright .................................................................................................................................... 23
format ..................................................................................................................................................... 23
regexp ..................................................................................................................................................... 24
regsub ..................................................................................................................................................... 25
Array........................................................................................................................................................ 25
array exists .......................................................................................................................................... 25
array names ........................................................................................................................................ 26
array size ............................................................................................................................................. 26
array get .............................................................................................................................................. 26
array set .............................................................................................................................................. 26
array startsearch ................................................................................................................................. 27
array nextelement............................................................................................................................... 27
array anymore ..................................................................................................................................... 28
array donesearch ................................................................................................................................ 28
Accessing Files......................................................................................................................................... 29
Open.................................................................................................................................................... 29
Close .................................................................................................................................................... 29
Gets ..................................................................................................................................................... 29
Puts ..................................................................................................................................................... 30
3

Read .................................................................................................................................................... 30
Seek ..................................................................................................................................................... 30
tell ....................................................................................................................................................... 31
flush..................................................................................................................................................... 31
eof ....................................................................................................................................................... 31
Glob ......................................................................................................................................................... 33
File status ................................................................................................................................................ 34
file size................................................................................................................................................. 34
file atime ............................................................................................................................................. 34
file mtime ............................................................................................................................................ 34
file exists ............................................................................................................................................. 34
File isdirectory ..................................................................................................................................... 35
file isfile ............................................................................................................................................... 35
file owned ........................................................................................................................................... 35
file executable ..................................................................................................................................... 35
file readable ........................................................................................................................................ 36
file writable ......................................................................................................................................... 36
file type ............................................................................................................................................... 36
File lstat ............................................................................................................................................... 37
file stat ................................................................................................................................................ 37
File System .............................................................................................................................................. 38
file readlink ......................................................................................................................................... 38
file copy ............................................................................................................................................... 38
file rename .......................................................................................................................................... 38
file delete ............................................................................................................................................ 39
file mkdir ............................................................................................................................................. 39
File and Path Names ............................................................................................................................... 39
file dirname ......................................................................................................................................... 39
file extension ....................................................................................................................................... 40
file rootname ...................................................................................................................................... 40
file tail ................................................................................................................................................. 40
file nativename ................................................................................................................................... 40
4

file normalize ...................................................................................................................................... 41
file split ................................................................................................................................................ 41
file attributes....................................................................................................................................... 41
file link ................................................................................................................................................. 42
file pathtype ........................................................................................................................................ 42
file separator ....................................................................................................................................... 43
file system ........................................................................................................................................... 43
file volumes ......................................................................................................................................... 43
Exec ......................................................................................................................................................... 43
Info Commands ....................................................................................................................................... 44
info args............................................................................................................................................... 44
info body ............................................................................................................................................. 44
info cmdcount ..................................................................................................................................... 44
info commands ................................................................................................................................... 45
info exists ............................................................................................................................................ 45
info globals .......................................................................................................................................... 46
info hostname ..................................................................................................................................... 46
info library ........................................................................................................................................... 46
info nameofexecutable ....................................................................................................................... 46
info patchlevel..................................................................................................................................... 47
info procs ............................................................................................................................................ 47
info script ............................................................................................................................................ 47
info sharedlibextension....................................................................................................................... 47
info tclversion ..................................................................................................................................... 47
info vars............................................................................................................................................... 47
Source command .................................................................................................................................... 48
Package Commands ................................................................................................................................ 48
package provide .................................................................................................................................. 49
pkg_mkIndex ....................................................................................................................................... 49
package require .................................................................................................................................. 49
Eval Command ........................................................................................................................................ 50

5

......... Audible alert (Bell) ........... Form Feed (Clear screen) ………….In Braces Assigning values to variables (set command) Set command used to set variables.In Braces} Hello World ......... \x08 \f ... Backslash Sequence string output hex value \a .............variable % Evaluations and Substitutions Using “ “ (Quotes) In Tcl... \x0c 6 ............. the evaluation of a command is done in two phases.....\x07 \b ....... a substitution phase and a command evaluation phase.................In quotes" Hello World ......24 % %puts $X This is a string % %puts $Y 1............Simple Text output (puts command) % puts "Hello World ...........24 % %puts “The string is : $X” The string is : This is a string ‘Unset’ command used to unset/remove a variable % set x 5 5 % puts $x 5 % unset x %puts $x can't read "x": no such variable ---.In quotes % % puts {Hello World .. Backspace . % set X "This is a string" This is a string % % set Y 1.....

........... Vertical Tab ................A back slash removes the meaning of the following character Using {} (braces) % set name "BillGates" BillGates % % puts {My name is $name} My name is $name % % puts "My name is $name" My name is BillGates % % puts {"My name is $name"} "My name is $name" % % puts "{My name is $name}" {My name is BillGates} % ---.............................. Carriage Return .......A-F....\x0a \r ...................................... d = 0-7 \xhh ................................. h = 0-9......... Tab ....................................................... \x09 \v ...................... \x0d \t ...................a-f % set a 10 10 % % puts "a value is : $a" a value is : 10 % % puts "a value is : \$a" a value is : $a % -------.......................... Octal value ..\n ........ \x0b \ddd .........No substitution happens with in the braces ----Substitution happens with in the quotes ----Observe the quotes with in braces ----Observe the braces with in quotes Using [ ] (Brackets) % set y [set x "def"] def % % puts "X value is : $x" X value is : def % % puts "Y value is : $y" Y value is : def % 7 ....................... New Line ................... Hex value .

grouped in decreasing order of precedence: -+~! Unary minus. Valid for any numeric operands. abs acos asin atan atan2 bool ceil cos cosh double entier exp floor fmod hypot int isqrt log log10 max min pow rand round sin sinh sqrt srand tan tanh wide OPERATORS The valid operators are listed below. | Bit-wise OR. The remainder will always have the same sign as the divisor and an absolute value smaller than the divisor. 1 otherwise. and remainder may be applied only to integers. remainder. & Bit-wise AND. ^ Bit-wise exclusive OR. bit-wise NOT. Valid for integer operands only. Produces a 1 result if both operands are non-zero. and bit-wise NOT may be applied only to integers. << >> Left and right shift. Valid for numeric operands only (integers or floating-point). divide. || Logical OR. */% Multiply. logical NOT. Valid for integer operands only. Valid for integer operands only. x?y:z 8 . Produces a 0 result if both operands are zero. None of these operators may be applied to string operands.Math functions Tcl supports the following mathematical functions in expressions. && Logical AND. +Add and subtract. Valid for numeric operands only (integers or floating-point). 0 otherwise. None of these operators may be applied to string operands. unary plus. Valid for integer operands only.

patterns or parameters which are mentioned in ?? are the optional.2) 9.0 % % expr ceil(2. Note: args.. % set x 10 10 % set y 15 15 % % expr $x + $y 25 % % expr $x * $y 150 % % expr pow(3. % set x 10 10 % % switch $x 10 { puts "X value is : $x" } X value is : 10 %switch $x { "10" { puts "X is : $x " } default { puts "No match found" } } X is : 10 % % switch $x { abc { puts "abc found" } default { puts "No match found" } } No match found 9 .0 % % expr floor(2.?patternN bodyN? ?default? If no match found it goes to default. The x operand must have a numeric value. Otherwise the result is the value of z.If-then-else..999) 3.0 % Switch command switch string pattern1 body1 ?pattern2 body2?. as in C. then the result is the value of y.345) 2. If x evaluates to non-zero.

If command Syntax : if expr1 ?then? body1 elseif expr2 ?then? body2 elseif .“incr” command used to increment a variable(Default increment value 1.else command % if { $x < 10 } { puts "X value is lessthan 10" } elseif { $x > 10 } { puts "X value is greater then 10" } else { puts "X value is equals to 10" } X value is equals to 10 % While Loop % set x 1.... ---------.” } x is 1 x is 2 x is 3 x is 4 % 10 .else command % if { $x == 15 } { puts "X values is : 15" } else { puts "X values is not equals to 15" } X values is not equals to 10 % If …elseif…. ?else? ?bodyN? A simple ‘if’ command % if { $x == 10 } { puts "X values is : 10" } X values is : 10 % If. incr x. 1 % % while {$x < 5} { puts "x is $x".

---.For loop Synatax : for start test next body % for { set i 0} {$i <= 2} {incr i} { puts "i value is : $i" } i value is : 0 i value is : 1 i value is : 2 % Procedures Syntax#1 proc name args body % proc sum {arg1 arg2} { set x [expr $arg1+$arg2].3+ default value of arg2 (5) = 8 11 .Here only one argument passed to the proc.} In this case if we miss the argumet.. it will take the default value provided in the arguments list.. % proc sum { arg1 {arg2 5} } { set x [expr $arg1+$arg2]. return $x } % % puts " The sum of 2 + 3 is: [sum 2 3]" The sum of 2 + 3 is:5 % % Syantax#2 proc example {required {default1 a} {default2 b} args} {. return $x } % % puts "Sum of 3 and 4 is : [sum 3 4]" Sum of 3 and 4 is : 7 % % puts "Sum of 3 and default value is : [sum 3]" Sum of 2 and default value is : 8 % ---.

Declaring 'x' as global variable incr x. puts "X value in side proc is: $x" } % % test X value in side proc is: 6 % % puts "Now X value is: $x" Now X value is: 6 % % 12 . -------------------.Global %set x 5 5 %puts "X value is: $x" X values is: 5 % %proc test { } { puts " X value in side proc is: $x } % %test can't read "x": no such variable -----proc test is not aware of variable x defined outside the procedure while executing "puts "X value is:$x"" (procedure "test" line 2) invoked from within "test" % % proc test { } { global x.

---------------..... $variable $value myvar : $myvar.Finally this will refer the value 'x' in global space. one: Z: 5 two: Z: 5 A: 5 % % puts "\nX: $x Y: $y" X: 2 Y: 1 % % 13 . set z 1. } % % % SetPositive x 5. --------. to z." return $myvar. to 'a' in this proc.Upvar Syntax : upvar ?level? otherVar1 myVar1 ?otherVar2 myVar2 ... 5 upvar 2 x a. to 'z' in this proc.} -. --------.e. Now 'z' gets the value of 'y' i.Converting a variabel to +ve value puts ". } % % one y.e one level up). % %puts "X : $x Y: $y\n" X : 5 Y: 5 % % proc two {k} { upvar 1 $k z . ---------------. two z.Giving reference of 'x' in global space(i.} else {set myvar $value. } % % proc one {y} { upvar $y z.Giving reference of 'z' in proc one(i.Giving reference of 'y' in global space. set a 2. if {$value < 0} { set myvar [expr -$value].e two levels up).. Now this 'z' gets the value of 'z' in proc one i. Now a gets the value of 'x' i. 5 puts "one: Z: $z".e.e....Finally this will refer the value 'y' in global space. -----.. % SetPositive y -5.. 5 puts "two: Z: $z A: $a".? Example #1 % proc SetPositive {variable value } { upvar $variable myvar..

% % proc test { } { upvar y z.Example #2 % set x 10. puts "---.z refers \'y\' value : $z ----" set z 20. puts "---.k refers 'x' value: 10 ---% % puts "Now x became : $x" Now x became : 5 % % 14 . --------------.This will reflect in 'x' value } % % test2 ---.This will reflect in 'y' value test2 } % % test ---.z refers 'y' value : 15 ---% % puts "Now y became : $y" Now y became : 20 % % % proc test2 { } { upvar 2 x k.k refers \'x\' value : $k ----" set k 5. ---------------. % set y 15.

set lst [list "item 1" "item 2" "item 3"] %set lst [list "item 1" "item 2" "item 3"] {item 1} {item 2} {item 3} % %puts "List values are : $lst" List values are : {item 1} {item 2} {item 3} % % % set lst [split "24/01/1985" "/"] 24 01 1985 % % % puts "List values are : $lst" List values are : 24 01 1985 % % lindex Syntax: lindex list index ----..item 2.Index values starts from '0' % set lst " 1 2 3 4 5 6 7 8" 12345678 % % puts "[lindex $lst 3]" 4 % % llength Syntax."] ------> split string ?splitChars? Splits the string into a list of items at splitChars.? set lst {{item 1} {item 2} {item 3}} set lst [split "item 1. llength list % % puts [llength $lst] 8 % 15 .List Syntax : list ?arg1 arg2 ..item 3" ".

.e..It replaces the 2 to 5 index values with the given numer % % puts " New list : $newlst" New list : 1 2 3456 7 8 9 10 % % % puts " Old list : $lst" Old list : 1 2 3 4 5 6 7 8 9 10 % % 16 .lappend Syntax: lappend listName ?arg1 arg2 ..Inserted '44' at index '3' i.9 and 10 appended at the end of the list 'lst' % % linsert Syntax : linsert list index arg1 ?arg2 . argn? % puts "[linsert $lst 3 44]" 1 2 3 44 4 5 6 7 8 9 10 ----------. as a fourth value in the list.. argn? % set newlst [lreplace $lst 2 5 3456] ----. % % % set newlst [linsert $lst 3 44] % % puts "New list : $newlst" New list : 1 2 3 44 4 5 6 7 8 9 10 % % puts "Old list lst is : $lst" Old list lst is : 1 2 3 4 5 6 7 8 9 10 -----.. argn? % lappend lst 9 10 % % puts "$lst" 1 2 3 4 5 6 7 8 9 10 ------------.No change in the original list % lreplace Syntax : lreplace list first last ?arg1 ..

Matches one occurrence of any character within the brackets. globbing wildcards are: * --. Globbing is the wildcarding technique that the shell uses. etc) -decreasing : Largest items first % set lst " 5 3 1 2 02 001 10 7 6 4 9 8" % % puts [lsort $lst] 001 02 1 10 2 3 4 5 6 7 8 9 17 . [a-z] will match any lower case letter.. [. % set list "{Washington 1789} {Adams 1797} {Jefferson 1801} {Madison 1809} {Monroe 1817} {Adams 1825}" % % puts "Jefferson is found at index : [lsearch $list Jefferson*]" Jefferson is found at index : 2 % % puts "Madison is found at index : [lsearch $list *diso*]" Madison is found at index : 3 % % lsort Syntax : lsort -option list Options are. Using the backslash lets you use glob to match a * or ?. For example.The backslash escapes a special character in globbing just the way it does in Tcl substitutions.returns the index value of the pattern in the list. if pattern found Value '5' is found at index value: 4 % % By default. a comes before B.Matches one occurrence of any character \X --.. A range of characters can be matched by using a range between the brackets.Matches any quantity of any character ? --. lsearch uses the globbing method of finding a match.] --. -dictionary : Dictionary order (2 comes before 10.lsearch Syntax: lsearch list pattern % set lst "1 2 3 4 5 6 7 8 9 10" % puts "Value '5' is found at index value: [lsearch $lst 5]" ---.

argn? % set list1 "1 2 3 4 5" 12345 % % set list2 "a b c d e" abcde % % % set list3 [concat $list1 $list2] 12345abcde % % % puts "Now list3 is : $list3" Now list3 is : 1 2 3 4 5 a b c d e % % 18 .% % puts [lsort -decreasing $lst] 9 8 7 6 5 4 3 2 10 1 02 001 % % puts [lsort -dictionary $lst] 1 001 2 02 3 4 5 6 7 8 9 10 % lrange Syntax : lrange list first last % set lst "1 2 3 4 5 6 7 8 9 10" % % puts [lrange $lst 3 7] 45678 % % concat Syntax: concat ?arg1 arg2 ...

.String command string length Syntax: string length string Returns the length of string % set string "this is my test string" % % puts "Length of the string is : [string length $string]" Length of the string is : 22 % % string index Syntax: string index string index Returns the char at the given index position in string. 19 . If string1 is greater than string2 These comparisons are done lexicographically............ not numerically.... If string1 is less than string2 * 0 ... If string1 is equal to string2 * 1 .. % set string "My Name Is Surya" % % puts "[string index $string 3] is the second character in \"$string\"" N is the second character in "My Name Is Surya" % % string range Syntax: string range string first last Returns a string composed of the characters from first to last % set string "this is my test string" % % puts "\"[string range $string 5 10]\" are characters between the 5'th and 10'th" "is my " are characters between the 5'th and 10'th % % string compare Syntax: string compare string1 string2 Compares string1 to string2 and returns * -1 .

this is test message" 10] 20 --------.string1 is equlas to string2 % string first Syntax: string first string1 string2 ?startIndex? Searches for string1 in string2 and returns the index value in string2 if string found.'is' found at 8th position in the second string % % puts [string first "is" "my name is surya. Returns index value if string1 found in string2.string1 is greater than string2 % % set string1 " Hello World " % % set string2 " This is test message " % % puts [string compare $string1 $string2] -1 ----------------. % puts [string first "this" "hello world. Other wise returns -1. this is test message"] 8 --------.string1 is less than string2 % set string1 " Hello" % % set string2 " Hello" % % puts [string compare $string1 $string2] 0 ----------------.'is' found at 20th position after index value '10' % string last Syntax: string last string1 string2 ?startIndex? Searches for string1 in string2 from the last. Otherwise returns -1.% set string1 "Surya" % % set string2 "Gadde" % % puts [string compare $string1 $string2] 1 ----------------. this is test message"] 13 --------.String 'this' found at index 13 in the second string % % puts [string first "is" "my name is surya. 20 .

But it returns last match. % string match Syntax: string match ?-nocase? pattern string % puts [string match "*ampl*" "this is sample message"] 1 --.After starting from the given index '12'th pisition. % puts [string wordstart "hello world test message" 0] 0 ----. % puts [string wordend "hello world test message" 0] 5 ----. a word end found at 16th position.It searches for the nearest word before index '8' and found a word started at index '6' % % puts [string wordstart "hello world test message" 20] 17 ----. this is test message" ] 23 --------------. % % puts [string wordend "hello world test message" 12] 16 ----.found pattern "*ampl* at "sample" % 21 . a word started at index '17' % string wordend Syntax: string wordend string index Searches for the word end after the given index value.it starts searching for 'is' from index value '20' to the start index.Before index '20'.'is' found at 8th.After starting from the given index '0' a word end found at '5'th index.% puts [string last "is" "my name is surya. % % puts [string last "is" "my name is surya. % string wordstart Syntax: string wordstart string index Searches for the starting of word after the given index value. this is test message" 20] 8 --------------. 20th and 23 rd positions.It searches for the word 'tcl' towards start of the sting from the given index '0' and the word found at 0'th position and returned '0' % % puts [string wordstart "hello world test message" 8] 6 ----.

string tolower Syntax: string tolower string -----. By default trimChars are whitespace (spaces. tabs. newlines) % puts [string trim " hello world "] hello world % % puts [string trim "hi ---. tabs. By default trimChars are whitespace (spaces. newlines) % puts [string trimleft " hello world " ] hello world % % puts [string trimleft "hello world" he] llo world 22 .hello world-------.Convert a string/word to upper case % puts [string tolower " hello world "] HELLO WORLD % string totitle Syntax: string totitle string -----.hello world----% string trimleft Syntax: string trimleft hi" hi] string ?trimChars? trimChars removed from the left.Convert a string/word to lower case % puts [string tolower "HELLO WORLD"] hello world string toupper Syntax: string toupper string -----.Convert first letter of the stirng/word to Upper case % puts [string totitle " hello world "] Hello world string trim Syntax: string trim string ?trimChars? trimChars removed from both ends.

By default trimChars are whitespace (spaces. 23 .59997"] puts "\n Example of format:\n" puts "$labels" puts "$price1" puts "$price2" puts "$price3" puts "$price4" Output: Example of format: Item Tomatoes Peppers Onions Steak Cost 30 Cents Each 20 Cents Each 10 Cents Each 3.string trimright Syntax: string trimtrim string ?trimChars? trimChars removed from the right.. tabs..60 per Lb.2f per Lb." "Steak" "3. argN? set labels [format "%-20s %+10s " "Item" "Cost"] set price1 [format "%-20s %10d Cents Each" "Tomatoes" "30"] set price2 [format "%-20s %10d Cents Each" "Peppers" "20"] set price3 [format "%-20s %10d Cents Each" "Onions" "10"] set price4 [format "%-20s %10. newlines) % puts [string trimright " hello world " ] hello world % % puts [string trimright "hello world" rld] hello wo format Syntax: format formatString ?arg1 arg2 .

.Matches any count (0-n) of the previous character + ----. Regular expressions can be expressed in just a few rules.Matches any single character * ----.Matches any character of a set of characters [^..Matches the end of a string .. Example : set sample "Where there is a will. ^ ----. subMatchN? Searches string for the regular expression exp.Matches any count..Matches any character *NOT* a member of the set of characters following the ^.] ----. (.Matches the beginning of a string $ ----... There is a way.Groups a set of characters into a subSpec.) ----. but at least 1 of the previous character [. [a-z]+ matches any lowercase word [A-Z]+ matches any uppercase words \s+ matches any number of spaces [a-zA-z0-9] matches any alpha-numberic word with any case 24 ..] ----." set result [regexp {[a-z]+} $sample match] puts "Result: $result match: $match" set result [regexp {([A-Za-z]+) +([a-z]+)} $sample match sub1 sub2 ] puts "Result: $result Match: $match 1: $sub1 2: $sub2" Output: Result: 1 match: here Result: 1 Match: Where there 1: Where 2: there [0-9]+ or \d+ matches any numeric string. ----..regexp Syntax: regexp ?switches? exp string ?matchVar? ?subMatch1 .

% if {[array exist array1]} { puts "array1 is an array" } else { puts "array1 is not an array" } array1 is an array % 25 . set sample "Where there is a will. Array We can define arrays in three types. 1) array set array1 [list {123} {Abigail Aardvark} {234} {Bob Baboon} {345} {Cathy Coyote}] 2) array set array1 { {123} {Abigail Aardvark} {234} {Bob Baboon} {345} {Cathy Coyote} } 3) set array1(123) "Abigail Aardvark" set array1(234) "Bob Baboon" set array1(345) "Cathy Coyote" % puts $array1(234) Bob Baboon % array exists Syntax: array exists arrayName Returns 1 if arrayName is an array variable. proc. or does not exist." regsub "way" $sample "lawsuit" sample2 puts "New: $sample2" Output: New: Where there is a will. There is a lawsuit.regsub Syntax: regsub ?switches? exp string subSpec varName Searches string for substrings that match the regular expression exp and replaces them with subSpec. There is a way. Returns 0 if arrayName is a scalar variable.

If pattern is supplied. only those indices that match pattern are returned. %puts "Size of the array1 is: [array size array1]" 3 % array get Syntax: array get arrayName % puts [array get array1] 345 {Cathy Coyote} 234 {Bob Baboon} 123 {Abigail Aardvark} % array set Syntax: array set arrayName dataList Converts a list into an associative array.array names Syntax: array names arrayName ?pattern Returns a list of the indices for the associative array arrayName. % puts "Array1 has the following entries: \n [array names array1] \n" 345 234 123 array size Syntax: array size arrayName Returns the number of elements in array arrayName. % puts [array set array1 {456 "hello World"}] % % puts "Size of the array1 is: [array size array1]" 4 % puts [array get array1] 345 {Cathy Coyote} 234 {Bob Baboon} 123 {Abigail Aardvark} 456 {hello World} 26 .

no elements in array to show % 27 .searchID % array nextelement Syntax: array nextelement arrayName searchID Returns the index of the next element in arrayName. then an empty string is returned. % puts [array startsearch array1] s-1-array1 ------.There are two methods for iterating through the contents of an associative array. and returns the searchID token that must be passed to those commands.  Using a foreach loop with the output from the array names command  Using the array startsearch commands Method#1 % foreach id [array names array1] { puts "$array1($id) has ID: $id" } Cathy Coyote has ID: 345 Bob Baboon has ID: 234 Abigail Aardvark has ID: 123 hello world has ID: 456 Method #2 array startsearch Syntax: array startsearch arrayName Initializes arrayName for use with the iterating commands. If there are no more elements in arrayName. % puts [array startsearch array1] s-1-array1 % puts [array nextelement array1 s-1-array1] 345 % puts [array nextelement array1 s-1-array1] 234 % puts [array nextelement array1 s-1-array1] 123 % puts [array nextelement array1 s-1-array1] 456 % puts [array nextelement array1 s-1-array1] ----.

% puts [array startsearch array1] s-1-array1 % % puts [array anymore array1 s-1-array1] 1 % puts [array donesearch array1 s-1-array1] % % puts [array anymore array1 s-1-array1] -------couldn't find search "s-1-array1" -----. it returns 0. % puts [array startsearch array1] s-1-array1 % % puts [array anymore array1 s-1-array1] 1 % puts [array nextelement array1 s-1-array1] 345 % puts [array anymore array1 s-1-array1] 1 % puts [array nextelement array1 s-1-array1] 234 % puts [array anymore array1 s-1-array1] 1 % puts [array nextelement array1 s-1-array1] 123 % puts [array anymore array1 s-1-array1] 1 % puts [array nextelement array1 s-1-array1] 456 % puts [array anymore array1 s-1-array1] 0 --------. This command should be executed when an iteration is complete.array anymore Syantax: array anymore arrayName searchID Returns a 1 if there are still elements in arrayName to be returned by nextelement. Otherwise.There are no elements in the array array donesearch Syntax: array donesearch arrayName searchID Destroys the state information associated with the iteration commands.searchID got destroyed while executing "array anymore array1 s-1-array1" 28 .

gets returns the number of characters read (or -1 if an EOF occurs).Open the file for reading and writing. The file must already exist. If the file does not exist..Open the file for writing..Open the file for reading.Accessing Files Tcl supports an interface to the file system using the buffered i/o mechanism..Open the file for writing. Set the current location to the end of the file. The file must already exist. The default is rw-rw-rw(0666).. = a. Open Syntax: open fileName ?access? ?permission? Opens a file and returns a token to be used when accessing the file..... or set the length to zero if it does exist. * permission is an integer to use to set the file access permissions... * FileName is the name of the file to open. = w. = r+ ... create it. 29 . Close Syntax: close fileID Closes a file previously opened with open. Gets Synatx: gets fileID ?varName? Reads a line of input from FileID. = a+. Create the file if it doesn't exist.. and flushes any remaining output.Open the file for writing. If there is a varName argument..Open the file for reading and writing... * access is the file access mode = r .. The file must already exist. Set the current location to the end of the file. Create the file if it doesn't exist. = w+.. and places the line of input in varName.. or set the length to zero if it does exist.

FileID is one of: * The value returned by a previous call to open with write access. Any existing end of file condition is cleared before the read command is executed... but can be set to the beginning of the file for reading. = end. Syntax#2 read fileID numBytes Reads up to numBytes from fileID... then the last character will be discarded if it is a newline... The position from which the offset is measured defaults to the start of the file.. * origin is the position to measure offset from.. = current... * fileID is one of: = a File identifier returned by open = stdin = stdout = stderr * offset is the offset in bytes at which the current position is to be set. and returns the input as a Tcl string.. It defaults to the start of the file. Note that if the file was opened with "a" access that the current position can not be set before the end of the file for writing. Any existing end of file condition is cleared before the read command is executed..Offset is measured from the end of the file... Seek Syntax: seek fileID offset ?origin? Change the current position within the file referenced by fileID.Offset is measured from the current position in the file.. or the end by setting origin appropriately.. but can be from the current location. Origin must be one of: = start. If -nonewline is set.. 30 ... and returns that string.Offset is measured from the start of the file. * stdout * stderr Read Syntax#1 read ?-nonewline? fileID Reads all the remaining bytes from fileID.Puts Synatx: puts ?-nonewline? ?fileID? string Writes the characters in string to the stream referenced by fileID(writes at the end)..

eof Syntax: eof fileID returns 1 if an End Of File condition exists.closing the previously opened file 31 .gets reads only one line This is line1 % % gets file5 This is line2 % % read file5 ------.read reads remaining This is line3 This is line4 % % % read file5 ----. Examples: % cat myfile This is line1 This is line2 This is line3 This is line4 % % open myfile r file5 % % gets file5 ------. otherwise returns 0. flush Syntax: flush fileID Flushes any output that has been buffered for fileID.nothing to read % % close file5 ----.tell Syntax: tell fileID Returns the position of the access pointer in fileID as a decimal string.

overwritten the file This is new line adding to the file This is another line adding to the file % 32 .gets the current position to the end of the line is line1 % % tell file5 ---.writing another line % % close file5 % % cat myfile ----.Opens file for writing file5 % % puts file5 "This is new line adding to the file" --.writing a line % puts file5 "This is another line adding to the file" --.returns the position number 14 % % close file5 % % open myfile w --.reads only 10bytes This is li % % gets file5 -----.get the current position to end of the line ne1 % % gets file5 This is line2 % % seek file5 0 start ---.% cat myfile This is line1 This is line2 This is line3 This is line4 % % open myfile r file5 % % read file5 10 ----.seek the position to the ‘0’th byte from the start of the file % gets file5 This is line1 % % seek file5 5 start --.seek the position to the ‘5th’ byte from the start of the file % gets file5 -----.

Thrown an error as the file doesn’t exists no files matched glob pattern "/root/myfile1" % % glob -nocomplain /root/myfile1 ------.This is default Pattern follows the same matching rules as the string match globbing rule % glob /root/myfile ----. an error would be generated when the empty list was returned. Without this flag.% cat myfile This is line1 This is line2 This is line3 This is line4 % % % % open myfile a ----. ----.Returned the file /root/myfile % % glob /root/myfile1 ----.Doesn’t thrown any error even the file was not exists % 33 .New line appended at the end % % Glob Syntax: glob ?switches? pattern ?pattern? returns a list of file names that match pattern Switches may be one of: “-nocomplain” “--“ ---- Allows glob to return an empty list without causing an error.Opening a file for appedning file5 % % puts file5 "This appends at the end of the file" % close file5 % % % cat myfile This is line1 This is line2 This is line3 This is line4 This appends at the end of the file ---.

% % file size myfile 92 % file atime Syntax: file atime name Returns the number of seconds since 1/1/1970 when the file name was last accessed. % file atime myfile 1335162779 % file mtime Syntax: file mtime name Returns the time of the last data modification in seconds since Jan 1. Generates an error if the file doesn't exist. and the user has search access in all the directories leading to the file. a 0 is returned. % file mtime myfile 1335162776 % file exists Syntax: file exists name Returns a 1 if the file name exists. 1970.File status file size Syntax: file size name Returns the size of name in bytes. Otherwise. % file exists myfile 1 % % file exists nofile 0 % 34 .

1 root root 92 Apr 23 12:02 myfile % % file executable myfile 0 % chmod 755 myfile % % ls -l myfile -rwxr-xr-x 1 root root 92 Apr 23 12:02 myfile % % file executable myfile 1 35 . % ls -l myfile -rw-r--r-. otherwise returns 0.File isdirectory Syntax : file isdirectory name Returns 1 if file name is a directory. otherwise returns 0. % mkdir mydir % % file isdirectory mydir 1 % % file isdirectory not-a-dir 0 file isfile Syntax: file isfile name Returns 1 if file name is a regular file. otherwise returns 0. % file owned myfile 1 % % file owned /home/testuser/testfile 0 % file executable Syntax: file executable name Returns a 1 if file has execute permissions to the current user. % touch newfile % % file isfile newfile 1 % file isfile nofile 0 % file owned Syntax: file owned name Returns 1 if the file is owned by the current user. otherwise returns a 0.

........... % file writable myfile 1 % file type Syntax: file type name Returns a string giving the type of file name............1 root root 92 Apr 23 12:02 myfile % % file readable myfile 1 % file writable Syntax: file writable name Returns 1 if file has write permissions to the current user. Block oriented device * fifo................... % ls -l myfile -rw-r--r-..............................file readable Syntax: file readable name Returns 1 if it has read permissions to the current user............Normal file * directory................................Named socket % file type myfile file % % file type mydir directory % 36 ....... otherwise returns 0.............. which will be one of: * file........ otherwise returns 0.......Symbolic link * socket....................Directory * characterSpecial....Character oriented device * blockSpecial.....Named pipe * link..

.............group ID of the file's group * ino.. the values in varName will refer to the link.time of last file status change * dev..........user ID of the file's owner 37 .... if name is a symbolic link.... The indexes in varName are: * atime.. The results are placed in the associative array varName......group ID of the file's group * ino.... The results are placed in the associative array varName...file size.number of hard links * size...Type of File * uid.......inode protection mode * mtime...................time of last file status change * dev....number of hard links * size......................time of last data modification * nlink.... file stat Syntax: file stat name varName This returns the same information returned by the system call stat....user ID of the file's owner Because this calls lstat...inode's number * mode........time of last data modification * nlink.......file size..File lstat Syntax: file lstat name varName This returns the same information returned by the system call lstat.....inode's device * gid. in bytes * type.......inode protection mode * mtime........ The indexes in varName are: * atime....inode's device * gid......inode's number * mode..................................... not the file that is linked to.....time of last access * ctime..Type of File * uid..time of last access * ctime...... in bytes * type.

If name isn't a symlink. % file copy myfile myfile1 % % file copy myfile myfile1 error copying "myfile" to "myfile1": file already exists % % file copy -force myfile myfile1 % file rename Syntax: file rename ?--force? sourcePath targetPath Moves a file from the source path to the target. or can't be read. an error is generated.File System file readlink Syntax: file readlink name Returns the name of the file a symlink is pointing to. % file readlink myfile could not readlink "myfile": invalid argument % % ln -s myfile linkfile % % file readlink linkfile myfile % file copy Syntax: file copy ?--force? sourcePath targetPath Copies a file from the source path to the target. % ls myfile myfile1 % % file rename myfile myfile2 % % file rename myfile1 myfile2 error renaming "myfile1" to "myfile2": file already exists % % file rename -force myfile1 myfile2 % ls myfile2 % 38 . Will not overwrite a file unless the --force option is provided. Will not overwrite a file unless the --force option is provided.

". file dirname returns a ". % ls myfile % % file mkdir mydir % % ls mydir myfile % File and Path Names file dirname Syntax: file dirname name Returns the directory portion of a path/filename string. it returns a "/". If name contains no slashes. If the last "/" in name is also the first character. % file dirname /home/testuser/testdir /home/testuser % % file dirname /root/mydir /root % 39 .file delete Syntax: file delete ?--force? path Deletes a file or directory from the filesystem. % ls mydir myfile2 % % file delete myfile2 % % ls mydir % file mkdir Syntax: file mkdir ?--force? path Creates a new folder.

% file nativename ~/example.dir/test % % file rootname /home/testuser/testdir /home/testuser/testdir % file tail Syntax: file tail name Returns all of the characters in name after the last slash. then returns name. Useful when using exec to invoke a platform-native application that requires a pathname in the platform's format.file extension Syntax: file extension name Returns the file extension. % file rootname /root/test. % file tail /root/Desktop/mydir/myfile myfile % file nativename Syntax: file nativename path Returns the native name of a file. % file extension test.” character in the last component of name.tcl .dir/test.tcl % file rootname Syntax: file rootname name Returns all of the characters in name up to but not including the last “.sh % % file extension test. If the last component of name does not contain a dot.sh .txt /root/example.txt % 40 . Returns $name if name contains no slashes.dir /root/test.

returns full path % file split Syntax: file split path Splits a path into a list in which each list element is a folder name the last element may be a file name./myfile % % file normalize . % file join / home testuser testdir testfile /home/testuser/testdir/testfile % % file join home testuser testdir testfile home/testuser/testdir/testfile % file attributes Syntax#1 file attributes name % file attributes myfile -group root -owner root -permissions 00644 % Syntax#2 file attributes name ?option? % file attributes myfile -group root % % file attributes myfile -permissions 00644 % 41 ./myfile /root/myfile -----------../" components./myfile . % file split /home/testuser/testdir/testfile / home testuser testdir testfile % file join Syntax: file join list Converts a list of folders into a platform-native file path. % ls .file normalize Syntax: file normalize path Returns an absolute path without any "..../". or ".

Syntax#3 file attributes name ?option? value option value. then the path type is volumerelative. If name refers to a file relative to the current working directory on a specified volume. and this command returns the value of the link given by linkName (i. If name refers to a file relative to the current working directory. then the path type will be relative. that argument is assumed to be linkName. the path type will be absolute. % ls myfile % % ln -s myfile linkfile % % file link linkfile myfile % % file link -symbolic link2 myfile myfile % % % ls link2 linkfile myfile % file pathtype Syntax: file pathtype name If name refers to a specific file on a specific volume. then an error is returned.e. If linkName is not a link or its value cannot be read . % file pathtype ../myfile relative % % file pathtype /root/myfile absolute % 42 .. or to a specific file on the current working volume.? % file attributes myfile -permissions 00755 % % file attributes myfile -permissions 00755 % file link Syntax: file link ?-linktype? linkName ?target? If only one argument is given. the name of the file it points to).

If no file system accepts name. file system Syntax: file system name % file system /dev/hda2 native % file volumes Syntax: file volumes Returns the absolute paths to the volumes mounted on the system. an error is generated. % file volumes / % In Windows: puts [file volumes] A:/ C:/ D:/ M:/ Exec Syntax: exec ?switches? arg1 ?arg2? .file separator Syntax: file separator ?name? If no argument is given. Without any virtual filesystems mounted as root volumes. as a proper Tcl list.sh % % puts $a mydir myfile test.switch values are “ -keepnewline” and “--“ % set a [exec ls] mydir myfile test.sh % 43 . the command will always return “/”. since all filesystems are locally mounted. the filesystem responsible for that path is asked to return its separator character. on UNIX. ?argN? --. returns the character which is used to separate path segments for native files on this platform... % file separator / % If a path is given.

. % info cmdcount 358 % info cmdcount 366 % 44 . in order. Procname must be the name of a Tcl command procedure..? info args Syntax: info args procname Returns a list containing the names of the arguments to procedure procname.Info Commands Syntax: info option ?arg arg . % proc add { arg1 arg2} { return [expr $arg1+$arg2] } % % info args add arg1 arg2 % info body Syntax: info body procname Returns the body of procedure procname. Procname must be the name of a Tcl command procedure % info body add return [expr $arg1+$arg2] % info cmdcount Syntax: info cmdcount Returns a count of the total number of commands that have been invoked in this interpreter.

returns a list of names of all the Tcl commands in the current namespace. else 0 is returned. braces or parentheses. info exists Syntax: info exists varName Returns 1 if the variable named varName exists in the current context (either as a global or local variable). info complete $cmd. If pattern is specified. then a value of 1 is returned. including both the built-in commands written in C and the command procedures defined using the proc command. only those names matching pattern are returned. % set cmd { puts "hello world} % info complete $cmd 0 % set cmd { puts "hello world”}. % info commands tell socket subst open eof pwd glob list exec pid auto_load_index time unknown eval lrange fblocked lsearch auto_import gets case lappend proc break variable llength auto_execok return linsert error catch clock info split array if fconfigure concat join lreplace add source fcopy global switch auto_qualify update close cd for auto_load file append format read package set binary namespace scan trace seek while flush after vwait uplevel continue foreach lset rename fileevent regexp upvar unset encoding expr load regsub history interp exit puts incr lindex lsort tclLog string % % % info commands a* auto_load_index auto_import auto_execok array add auto_qualify auto_load append after % In the above output ‘add’ is defined by us in the previous step. % info exists var 0 % % set var 10 10 % % info exists var 1 % info complete Syantax: info comlete string If string has no unmatched brackets.info commands Syntax: info commands ?pattern? If pattern isn't specified. --------> Returns “1” 45 . returns 0 otherwise.

% info nameofexecutable /usr/bin/tclsh % 46 .info globals Syntax: info globals ?pattern? If pattern isn't specified. returns a list of all the names of currently-defined global variables. If pattern is specified.4 % info nameofexecutable Syntax: info nameofexecutable Returns the full path name of the binary file from which the application was invoked. % set var 10 10 % % set a 5 5 % proc test { } { global a return $a } % % info globals tcl_rcFileName tcl_version argv0 argv tcl_interactive a var auto_oldpath errorCode auto_path errorInfo auto_index env tcl_pkgPath tcl_patchLevel argc tcl_libPath tcl_library tcl_platform % info hostname Syntax: info hostname Returns the name of the computer on which this invocation is being executed. % info hostname localhost % info library Syntax: info library Returns the name of the library directory in which standard Tcl scripts are stored. Global variables are variables in the global namespace. % info library /usr/share/tcl8. only those names matchingpattern are returned.

% info sharedlibextension . % info procs auto_load_index test unknown auto_import auto_execok add auto_qualify auto_load history tclLog % % info procs t* test tclLog % info script Syntax: info script If a Tcl script file is currently being evaluated.13 % info procs Syntax: info procs ?pattern? Returns a list of all the names of Tcl command procedures in the current namespace.4 % info vars Syntax: info vars ?pattern? Returns a list of all the names of currently-visible variables.4. % info vars tcl_rcFileName tcl_version argv0 argv tcl_interactive a var b auto_oldpath errorCode auto_path errorInfo auto_execs auto_index env tcl_pkgPath tcl_patchLevel argc tcl_libPath tcl_library tcl_platform % % info vars a* argv0 argv a auto_oldpath auto_path auto_execs auto_index argc 47 .so % info tclversion Syntax: info tclversion Returns the value of the global variable tcl_version % info tclversion 8.info patchlevel info patchlevel Returns the value of the global variable tcl_patchLevel % info patchlevel 8. info sharedlibextension Syntax: info sharedlibextension Returns the extension used on this platform for the names of files containing shared libraries.

Source command Syntax: source filename The source command will load a file and execute it. 2 Include a line like this in the application that uses a package: package require nameOfPackage You script will need a separate package require command for each package you wish to include.tcl file to describe the files in the package. This command can be used to:  separate a program into multiple files. you'll need 1 to include a package provide command like package provide nameOfPackage revisionNumber in each file that's included in the package 2 create a pkgIndex. A package may consist of a single file.tcl puts "hello world" puts "This is sample tcl program" % % source test. The standard Tcl distributions include the proper paths by default.tcl hello world This is sample tcl program % Package Commands Tcl supports grouping multiple procedures or compiled "C" code modules into a single entity referred to as a package.  make a library file that contains all the procs for a particular set of functions. multiple files or a mix of compiled and Tcl script files. This can be done with the pkg_mkIndex command.  configure programs  load data files % cat test. To access a package from a script: 1 Make certain that the auto_path global variable includes the path to the package you wish to include. To create a package. 48 .

If the revision number is absent. % % cat myfile. Each proc in the files will be listed in the index file.0 % % add 2 3 5 % 49 . the largest revision available is used. % add 2 3 invalid command name "add" % % lappend auto_path /root/mydir /usr/share/tcl8. with a reference to the source code module that contains it.0 proc demoproc {} { puts "Running the demoproc" } proc add { a b } { set c [expr $a + $b] return $c } % pkg_mkIndex Syntax: pkg_mkIndex libdir file1 . A file may include only one package provide command.4 /usr/share /usr/lib /root/mydir % % package require demopkg 1. % pkg_mkIndex /root/mydir myfile..filen.tcl package provide demopkg 1.tcl % package require Syntax: package require name ?revision? Tells the interpreter to find a package with the given name and optional revision number.tcl) in libdir from the source code modules listed as file1 .package provide Syntax: package provide name revision Declares that this file provides an implementation of a specific revision of a package.. filen Creates an index file (pkgIndex.

and passed to tcl_Eval to evaluate and execute.argn as one or more Tcl commands. The args are concatenated into a string. % set i "set j 2" set j 2 % % set j can't read "j": no such variable % % eval $i 2 % % puts $j 2 % set i 1 1 % % eval puts $i 1 % % eval puts hello hello % % eval puts "hello wolrd" --------------------------------------> This is error case.Eval Command Syntax: eval arg1 ??arg2?? . The eval command will evaluate a list of strings as though they were commands typed at the % prompt or sourced from a file. ??argn?? Evaluates arg1 .. can not find channel named "hello" % % eval [list puts {hello world}] --------------------------------> Method-1 hello world % % eval [format {%s "%s"} puts "hello world"] --------------> Method-2 hello world % 50 . Eval returns the result (or error code) of that evaluation..

and the results placed in the return string. arguments are present. Subst performs a substitution pass without performing any execution of commands except those required for the substitution to occur. Some situations. ie: commands within [] will be executed. then that set of substitutions will not be done. In this case.. such as placing the name of a variable in a variable.Subst Command Syntax: subst ?-nobackslashes? ?-nocommands? ?-novariables? String If any of the -no. require two passes through the substitution phase.. the subst command is useful. % set a 1 1 % set c a a % % puts $$c $a % % puts [subst $$c] 1 % % puts "format with no subst [format {$%s} $c]" format with no subst $a % % puts "format with subst: [subst [format {$%s} $c]]" format with subst: 1 % % set a arrayname % set b index % set c newvalue % eval [format "set %s(%s) %s" $a $b $c] % puts "Index: $b of $a was set to: $arrayname(index)" Index: index of arrayname was set to: newvalue 51 . The Tcl interpreter does only one substitution pass during command evaluation.

52 .