Seta24 Setb15 Set C 23 Set D 85
Seta24 Setb15 Set C 23 Set D 85
Language Syntax
• 4Types of Substitution
• 1set
command assigns a value to a variable
set varName ?value?
set a 23; ==> 23
set msg “Hello World”; ==> Hello World
set msg ==> Hello World
• 2Variable Substitution
is triggered by the presence of an unquoted $ character.
set a 23; ==> 23
expr $a+2; ==> 25
• 3unset
command removes the variable.
unset varName ?varName varName?
unset a msg;
set msg ==>
• 4info exists
command test for the existence of a variable. It returns a 1
if the variable exists in the current context, 0 otherwise.
info exists varName
set a 32;
info exists a; ==> 1
unset a;
info exists a; ==> 0
• 5incr
command adds the specified integer to the variable’s value
and stores the value back into the variable.
incr varName ?increment?
set i 1;
incr i 3; ==> 4
set j 12;
incr j -2; ==> 10
incr j; ==> 11
• 6append
command adds text to the end of a variable in a way that
avoids character copying.
append varName value ?value ...?
set Msg “IOplace: ”
append Msg “Severe Error”
==> IOplace: Severe Error
• 7Predefined Variables
• 8argv0 contains the Tcl script name
• 9argc contains the number of arguments
• 10argv contains a list of the arguments
• 11env(Environment_Variable_Name) contains the value of the
specified environment variable.
args.tcl:
#!/usr/local/bin/tclsh
puts “The command name is \”$argv0\””
puts “There are $argc arguments: \ $argv”
puts “User is $env(USER)”
exit
> args.tcl p1 p2 p3
The command name is args.tcl
There are 3 arguments: p1 p2 p3
User is forman
Expressions
expr !2 ==> 0
expr 3*4 ==> 12
expr 5 < 4 ==> 0
expr 0x55&0xAA ==> 0xFF
expr 1?”A”:”B” ==> A
NOTE: Several math functions, such as
sin(x) and log(x) exist. See
references for details.
Control Flow
Table 1: if
command evaluates an expression, tests the results and if it is
non-zero, executes a script.
if test1 body1 ?elseif test2 body2 ...? ?else bodyn?
if {$x == 0} { set y 23 }
if {$y > 12} {
...
} elseif {$z < 2} {
...
} else {
... }
Table 1: while
command evaluates an expression and if the result is nonzero
then it executes the Tcl script. It repeats the processes until
the expression evaluates to zero.
while test body
set i 0
while { $i < 10 } {
puts “I=$i”
incr i
}
Table 1: for
command executes its initialization script, then evaluates its
test. If it evaluates to nonzero, then it executes its body script,
executes it reinit script and then reevaluates its test. It repeats
the process until the test evaluates to zero.
for init test reinit body
for {set i 0} {$i<10} {incr i} {
puts “I=$i”
}
Table 1: foreach
command evaluates its body script for each item in a list.
foreach varName list body
set users “John Scott Jerry”
foreach name $users {
puts “Name=$name”
}
Table 1: break
command terminates the innermost nested looping command
Table 1: continue
command terminates the current iteration of the innermost
looping command and goes on to the next iteration of that
command.
Table 1: switch
command tests a value against a number of patterns and
executes one of several Tcl scripts.
switch ?options? string {pattern body ?pattern body ...?}
options may be -exact, -glob, -regexp, or -- to indicate the end of
options.
switch $rotation {
ROT000 { set side “Bottom” }
ROT090 { set side “Right” }
ROT180 { set side “Top” }
ROT270 { set side “Left” }
default { set side “Error” }
}
switch -exact -- $option {
-p { set imagePDLname $arg }
-i -
-io { set placeFileName $arg }
default { puts “Error: invalid
option $option” }
}
Table 1: eval
command executes its arguments as a Tcl script.
eval arg ?arg arg ...?
set cmd “set a 0”
eval $cmd ==> 0
set cmd2 “Set b \$a”
set c [eval $cmd2] ==> 0
Table 1: source
command executes the contents of the specified file. It returns
the return value of the last command executed in the file. It
also allows a return command in the file to terminate
processing of the file.
source utilities.tcl
Data Structures
Strings
Strings are an ordered collection of characters. Tcl stores strings
using null (zero) character for termination.
Table 1: string length
command returns the number of characters in the specified
string.
string length string
string length “Hello World” ==> 11
Table 1: string index
command returns the charIndex’th character of string.
string index string charIndex
string index “Hello World” 5 ==> o
Table 1: string first
command returns the index in string2 of the first character in
the leftmost substring that exactly matches string1 or -1 if
there is no match.
string first string1 string2
set str “Outline=(100,100,(-100,-100))”
string first “(“ $str ==> 9
string first “,(“ $str ==> 17
Table 1: string last
command returns the index in string2 of the first character in
the rightmost substring that exactly matches string1 or -1 if
there is no match.
string last string1 string2
set str “Outline=(100,100,(-100,-100))”
string last “)“ $str ==> 29
Table 1: string range
command returns the substring of string that lies between the
indices given by first and last, inclusive.
string range string first last
set str “Outline=(100,100,(-100,-100))”
set tuple [string range $str 10 29]
==> 100,100,(-100,-100)
Table 1: string tolower
command returns a string which has been converted to all
lower case characters.
string tolower string
set lcase [string tolower “AbCdEf”
==> abcdef
Table 1: string toupper
command returns a string which has been converted to all
upper case characters.
string toupper string
sting toupper “AbCdEf” ==> ABCDEF
Table 1: string trim
command returns a string which has had specified leading and
trailing characters removed. The default characters for
removal are space, tab, newline, and carriage return.
string trim string ?chars?
set str “ PDLLengthUnit = MICRON;“
set str [string trim $str]
set str [string trim $str “;”]
Table 1: string trimleft
command returns a string which has had specified leading
characters removed.
string trimleft string ?chars?
set str “(100,100,(-100,-100))”
set str [string trimleft “(“]
==> 100,100,(-100,-100))
Table 1: string trimright
command returns a string which has had specified trailing
characters removed.
string trimright string ?chars?
set str “100,100,(-100,-100))”
set str [string trimright “)“]
==> 100,100,(-100,-100
Character Description
* Matches any seqence of zero or more characters
? Matches any single character
[chars] Matches any single character in chars. If chars
contains a sequence of the form a-b, any character
between a and b, inclusive will match.
\x Matches the single character x. This provides a
way to put the special characters *, ?, [,], and \ in
the pattern.
Table 1: regexp
command compares a string to a regular expression and
returns 1 if the pattern matches and 0 otherwise. The -nocase
option indicates that case should be ignored.
regexp ?-nocase? ?--? exp string
Table 1: Regular Expression Special Characters
Character Description
. Matches any single character
^ Matches the null string at the start of the string
$ Matches the null string at the end of the string
[chars] Matches any single character from chars. If the
first character of chars is ^, the pattern matches
any single character NOT in the remainder of
chars. A sequence of the form a-b in chars is
treated as all the characters between a and b,
inclusive.
(regexp) Matches anything that matches the regular
expression regexp.
* Matches a sequence of 0 or more matches of the
preceding atom.
+ Matches a sequence of 1 or more matches of the
preceding atom.
? Matches either a null string or a match of the
preceding atom.
regexp1| Matches anything that matches either regexp1 or
regexp2 regexp2
Character Description
d Signed Integer
u Unsigned Integer (Format command only)
i Signed Integer. The argument may be in hex (0x) or
octal (0) format.
o Unsigned Octal.
x or X Unsigned hexadecimal. ‘x’ gives lower-case results.
c Map from an integer to the ASCII character it
represents.
s A string.
f Floating Point number in the format a.b.
e or E Floating point number in scientific notation, a.bE+/-
c.
g or G Floating point number in either %f or %e format,
whichever is shorter.
Character Description
- Left justify the field
+ Always include a sign, either + or -.
space Precede a number with a space, unless the number
has a leading sign.
0 Pad with zeros.
# Leading 0 for octal. Leading 0x for hex. Always
include a decimal point in floating point. Do not
remove trailing zeros (%g).
Table 1: scan
command parses a string, using fields specified in a format
string, placing values that match % sequences into specified
variables.
scan string format varName ?VarName ...?
Lists
List are an ordered collection of elements where each element
can have any string value. Elements of a list can themselves be
lists.
set nameList John Jerry Joe
==> John Jerry Joe
set nameList { John Jerry {Mary Joe }}
==> John Jerry {Mary Joe}
Table 1: list
command returns a list whose elements are the command
arguments.
list value ?value ...?
list {a b c} {d e} f {g h}
==> {a b c} {d e} f {g h}
Table 1: concat
command takes any number of lists as arguments and joins all
the elements into a single list.
concat list ?list ...?
concat {a b c} {d e} f {g h}
==> a b c d e f g h
Table 1: llength
command returns the number of elements in a list.
llength list
llength {{a b c} {d e} f {g h}} ==> 4
llength John ==> 1
llength {} ==> 0
Table 1: lindex
command returns the index’th element of the list (0 refers to
the first element).
lindex list index
set cList {{a b c} {d e} f {g h}}
lindex $cList 2 ==> f
lindex $cList 0 ==> a b c
Table 1: lrange
command returns a list consisting of elements first through
last of list.
lrange list first last
lrange $cList 0 1 ==> {a b c} {d e}
lrange $cList 2 end ==> f {g h}
Table 1: lappend
command provides an efficient way to append new elements to
a list stored in a variable.
lappend varName value ?value ...?
lappend cList x y z
==> {a b c} {d e} f {g h} x y z
Table 1: split
command breaks a string into component pieces so that you
can process the pieces independently. It returns a list whose
elements are the pieces.
split string ?splitChars?
set y /u/home/tcl/lists.tcl
split $y / ==> u home tcl lists.tcl
Table 1: join
command concatenates the elements of a list with the specified
separator between them, to form a string.
join list ?joinString?
set x {5 12 7}
expr [join $x +] ==> 24
Arrays
Table 1: An array is a collection of elements, each of which is a
variable with its own name and value. Both array names
and element names may be arbitrary strings.
set Position(USAGE_A) “0,200”;
set Usage “USAGE_A”;
set xypos $Position($Usage); ==>0,200
Table 1: Multidimensional arrays can be simulated by concate-
nating multiple indices into a single element name.
set i 10; set j 20;
set matrix($i,$j) 254;
set value $matrix($i,$j); ==> 254
Table 1: array size
command returns the number of elements in an array.
array size arrayName
array size env ==> 21
Table 1: array names
command returns a list of the names of all the elements in an
array.
array names arrayName
array names env ==> HOME MANPATH ...
Table 1: Other array commands exist for searching through
arrays.
Input/Output Operations
Tcl I/O commands are very similar to “C” I/O library pro-
cedures. First the file must be opened, then data can be read or
written, and then the file must be closed.
Table 1: open
command is used to open the specified file. The access to the
file is controlled by passing an access flag. It returns a file ID
which can be used to access the file stream.
open name ?access? ?permissions?
Character Description
r Open for reading. File must exist.
r+ Open for reading and writing. The file must exist.
w Open for writing. Truncate if it exists. Create if it
does not exist.
w+ Open for reading and writing. Truncate or create.
a Open for writing. The file must exist. Data is
appended to the file.
a+ Open for reading and writing. File must exist. Data
is appended.
Table 1: close
command closes the file stream.
close fileId
Table 1: flush
command writes any buffered output that has been generated
for the specified file stream.
flush fileId
Table 1: puts
command writes a string to a I/O stream, appending newline
character unless the -nonewline option is specified. The
default I/O stream is stdout.
puts ?-nonewline? ?fileId? string
Table 1: gets
command reads a line from an I/O steam and places it into the
specified variable. It returns the number of characters read
or -1 if the end of file is reached. The default I/O stream is
stdin.
gets fileId ?varName?
#!/usr/local/bin/tclsh
# Unix cp like command in Tcl
set infID [open [lindex $argv 0]]
set outfID [open [lindex $argv 1] w]
while {[gets $infID line] >= 0} {
puts $outfID $line
}
close $infID
close $outfID
Table 1: cd
command changes the current working directory to the
specified directory or $HOME in none is specified.
cd ?dirName?
cd ==> /u/forman
Table 1: pwd
command returns the full path of the current working
directory.
pwd
pwd ==> /u/forman
Table 1: glob
command returns a list of names of all the files that match any
of the specified glob style patterns. An error occurs, if
-nocomplain is not specified and the returned list is empty.
glob ?-nocomplain? ?--? pattern
?pattern...?
glob -nocomplain *.tcl
==> abc.tcl even.tcl hello.tcl
Table 1: file exists
command returns 1 if the specified file exists and the current
user has search privilege for the directories leading to it, 0
otherwise.
file exists fileName
file exists /u/forman/.login ==> 1
Table 1: file readable
command
returns 1 if the file is readable by the current user, 0 oth-
erwise.
file readable fileName
file readable /u/forman/.login ==> 1
Table 1: file writable
command returns 1 if the file is writable by the current user, 0
otherwise.
file writable fileName
file writable /u/joes/file.txt ==> 0
Table 1: file executable
command returns 1 if the file is executable by the current
user, 0 otherwise.
file executable fileName
file executable /u/forman/hello.tcl
==> 1
Table 1: file owned
command returns 1 if the file is owned by the current user, 0
otherwise.
file owned fileName
file owned /u/joes/private/file.txt
==> 0
Table 1: file isfile
command returns 1 if the specified file is an ordinary file, 0
otherwise.
file isfile fileName
file isfile /u/forman/hello.tcl
==> 1
Table 1: file isdirectory
command returns 1 if the specified file is a directory, 0
otherwise.
file isdirectory fileName
file isdirectory /u/forman/hello.tcl
==> 0
file isdirectory /u/forman ==> 1
Table 1: file type
command returns a string giving the type of the specified file.
Its value will be one of file, directory, characterSpecial,
blockSpecial, fifo, link, or socket.
file type fileName
file type /u/forman/hello.tcl
==> file
HelpText
==> abc.tcl (I) abc.tcl a b c
Table 1: Defaults for procedure arguments can be defined using
a sublist which contains the arguments name and its default
value. Arguments with defaults, after any arguments
without defaults, are optional.
sum 1 2 3 ==> 6
sum 1 2 3 4 5 6 7 8 9 ==> 45
Table 1: return
command returns from the innermost nested procedure or
source command with the specified value as the result of the
procedure. If no value is specified, an empty string is
returned.
return ?value?
inrange 10 20 11 ==> 1
Table 1: When a Tcl procedure is executed it uses a local set a
variables. Variables referenced outside of any procedure
are called global variables. A procedure can reference
global variables using the global command.
Table 2: global
command binds local variables to global variables with the
same name.
global name1 ?name2 ...?
proc HelpText {} {
global argv0
puts “$argv0 (I) $argv0 a b c”
}
HelpText
==> hello.tcl (I) hello.tcl a b c
Table 1: A Tcl procedure can reference variables within its call
stack by using the upvar command. This command is also
useful for passing arrays and large lists to a procedure.
Table 1: upvar
command binds local variables to variables at the specified
stack level. The stack level consists of a number or a number
preceded by #, and defaults to 1. #0 specifies that the local
variables are bound to global variables.
printArray env
==> HOME = /u/forman
==> MANPATH = /usr/man:/usr/local/man
...
Table 1: uplevel
command evaluates its arguments, like eval, but in the
variable context of the specified stack level. This command is
useful in the generation of control structures.
uplevel ?level? arg ?arg ...?
proc do {Counter first last body} {
upvar $Counter cnt
for {set cnt $first} {$cnt<=$last} \
{incr cnt} {
uplevel $body
}
}
do i 2 4 {
puts “Count=$i”
}
puts “Last Count=$i”
==> Count=2
==> Count=3
==> Count=4
==> Last Count=4
==> abc.tcl
==> even.tcl
==> hello.tcl
Table 1: exit
command terminates the current process returning an integer
return code to the parent. The return code defaults to 0 if not
specified.
exit ?returnCode?
exit 3
Table 1: open
command can be used to create pipes to subprocesses. The
access to the subprocesses is controlled by passing an access
flag. It returns a file ID which can be used to communicate
with the subprocess with the gets and puts commands.
open |command ?access?
Table 1: pid
command returns a list of all the process IDs in the pipeline
associated with the specified file ID (opened using |). If no file
ID is specified it returns the process ID of the current process.
pid ?fileID?
pid ==> 19136