TCL Overview
TCL Overview
1
Course Pre-requisites
▪ Matrix Query Language
2
Course Objective
3
Session Outline
4
Language Highlights
5
Capabilities
6
Capabilities
▪ Procedures
User defined subroutines and functions
▪ File Access
Reading, writing, and manipulating files
▪ Process Execution
Running external programs
7
TCL commands/syntax
8
General Syntax
9
Tcl Commands
10
General Syntax
▪ Example:
set iNum 42
set iNum2 43; set iNum3 44
11
Variables
12
Variable Assignment
13
Accessing Variable Values
14
Accessing Variable Values
▪ Examples:
set sMyvar “Hard Disk”
puts $sMyvar
=> Hard Disk
set iCount 23
puts $iCount
=> 23
15
Substitution
16
Variable Substitution
▪ Dollar Signs ($) invoke variable substitution
▪ Used to access the contents of a variable
▪ Example:
set sOutput “Print this line”
puts $sOutput
==> Print this line
▪ Results:
The $ causes the sOutput variable to be replaced by it’s value
(Print this line) and the puts command prints it to standard out
17
Special Variable Substitution
18
Command Substitution
19
Command Substitution
▪ Example:
set iResult [ expr 2 + 2 ]
==> 4
▪ Results:
The [ ]’s cause the text inside to be executed as a Tcl
command. The result (4) is substituted for the [ ]s and
the text, and assigned to the variable.
20
Using MQL
21
Using MQL Commands
22
MQL Commands in Tcl
Examples:
▪ Display list of bus objects in Tcl
mql list bus
▪ Set variable to list of all persons in Matrix
set sPersons [mql list person]
▪ Set variable to print role output of Shipper
set sRole [mql print role Shipper]
23
Character Substitution
▪ Backslashes (\) invoke character substitution
The backslash and following character are removed and replaced
with a special character:
\a Audible alert
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Tab
\v Vertical tab
\ddd Octal value ddd
\xhh Hex value hh
\newline Single space
\(all other chars) The character
▪ Used to access special characters
24
Character Subsitution
25
Character Substitution
26
Character Substitution
▪ Results:
The \ newline on the first line continues the statement.
The \[ and \] prevent command substitution from
occurring on the attribute Source.
27
Grouping
28
Grouping
29
Double Quote Grouping
30
Double Quote Grouping
▪ Example:
set iNum 99
puts “The value of iNum is $iNum”
==> The value of iNum is 99
▪ Results:
The multiple words in the puts statement are grouped
with double quotes as one argument to puts. Double
quotes allow variable substitution to occur on $iNum.
31
Double Quote Grouping
▪ Example:
puts “Some text; and
more text”
==> Some text; and
==> more text
▪ Results:
Since the newline and semicolon are within double
quotes, they do not terminate the Tcl command. Also,
everything within the double quotes is considered to be
one word or argument to the puts command.
32
Brace Grouping
33
Brace Grouping
▪ Example:
set iCount 99
puts {The value of iCount is $iCount}
==> The value of iCount is $iCount
▪ Results:
The multiple words in the puts statement are grouped
with curly braces as one argument to puts. Curly braces
prevent variable substitution to occur on $iCount.
34
Brace Grouping
▪ Example:
puts {hello \n hello; $more [text]}
==>hello \n hello; $more [text]
▪ Results:
All of the special characters (space, \n, $, [, ], and ;) lose
their meaning and are printed as normal characters
35
Comments
36
Comments
37
More variable commands
38
More Variable Commands
39
incr Command
▪ Syntax:
incr varName ?increment?
▪ Description:
Adds increment (default of 1) to the contents of varName (integer) and
places the resulting value in varName
▪ Example:
set iSize 2
incr iSize 2
puts $iSize
==>4
40
append Command
▪ Syntax:
append varName value ?value …?
▪ Description:
Concatenates all the values and appends them to the end of the
variable, creating the variable if it doesn’t exist
▪ Example:
append sPartName Memory “ “ 128 MB
puts $sPartName
==>Memory 128MB
41
unset Command
▪ Syntax:
unset varName ?varName …?
▪ Description:
Removes variables(s) and their values from memory
▪ Example:
unset iSize sName
▪ Results:
The iSize and sName variables are deleted
42
Expressions
43
Expressions
44
Expression Commands
expr
45
Expr Command
▪ Syntax:
expr arg ?arg arg …?
▪ Description:
Concatenates all the arguments and evaluates them as an expression
▪ Example:
expr (10/2) + 3
==>8
▪ Results:
The expression is evaluated and returned as a string
46
Strings Processing
47
String and list processing
48
String Manipulation
49
String Commands
▪ The following commands are used to manipulate strings:
format string length
regexp string match
regsub string range
scan string tolower
string compare string toupper
string first string trim
string index string trimleft
string last string trimright
50
string length Command
▪ Syntax:
string length string
▪ Description:
Returns the length of the string
▪ Example:
string length “A test string”
==>13
▪ Results:
Returns the number of characters in the string, 13
51
string index Command
▪ Syntax:
string index string charIndex
▪ Description:
Returns the charIndex character of string, or an empty string if it
does not exist
▪ Example:
string index “Hello World” 4
==>o
▪ Results:
Returns the 4th character in the string, “o”
52
string range Command
▪ Syntax:
string range string first last
▪ Description:
Returns the substring of string that lies between the first and last
indices
▪ Example:
string range “A test string” 7 end
==>string
▪ Results:
The substring from character 7 to the end is returned
53
string first Command
▪ Syntax:
string first string1 string2
▪ Description:
Returns the first position where string1 is found in string2, or -1 if it
is not found
▪ Example:
string first “!” “Help!Me!”
==>4
▪ Results:
Finds the first ! at index 4 of the second string
54
string last Command
▪ Syntax:
string last string1 string2
▪ Description:
Returns the last position where string1 is found in string2, or -1 if it
is not found
▪ Example:
string last “!” “Help!Me!”
==>7
▪ Results:
Finds the last ! at index 7 of the second string
55
string compare Command
▪ Syntax:
string compare string1 string2
▪ Description:
Compares the string and returns -1, 0, or 1 if string1 is less than,
equal to, or greater than string2
▪ Example:
string compare “First” “Second”
==>-1
▪ Results:
“First” is less than “Second”, so a -1 is returned
56
string match Command
▪ Syntax:
string match pattern string
▪ Description:
Returns 1 if pattern matches string and 0 if it doesn’t
▪ Example:
string match “*test*” “A test string”
==>1
▪ Results:
The pattern matches the string, so a 1 is returned
57
string tolower Command
▪ Syntax:
string tolower string
▪ Description:
Return a lowercase version of string
▪ Example:
string tolower “A Test String”
==>a test string
▪ Results:
All the uppercase characters are converted to lowercase
58
string toupper Command
▪ Syntax:
string toupper string
▪ Description:
Return a uppercase version of string
▪ Example:
string toupper “A Test String”
==>A TEST STRING
▪ Results:
All the lowercase characters are converted to uppercase
59
string trim Command
▪ Syntax:
string trim string ?chars?
▪ Description:
Trims characters found in chars from each end of the string, default
is white space
▪ Example:
string trim “ A test string !!!!” “ !”
==>A test string
▪ Results:
Removes all spaces and !’s from each end of the string
60
string trimleft Command
▪ Syntax:
string trimleft string ?chars?
▪ Description:
Trims characters found in chars from the left end of the string, default
is white space
▪ Example:
string trimleft “ A test string !!!!” “ !”
==>A test string !!!!
▪ Results:
Removes all spaces and !’s from the left end of the string
61
string trimright Command
▪ Syntax:
string trimright string ?chars?
▪ Description:
Trims characters found in chars from the right end of the string, default
is white space
▪ Example:
string trimright “ A test string !!!!” “ !”
==> A test string
▪ Results:
Removes all spaces and !’s from the right end of the
string
62
regexp Command
▪ Syntax:
regexp exp string
▪ Description:
Returns 1 if regular expression exp matches all or part of
string, otherwise it returns 0
63
regexp Command
▪ Example:
regexp "does|match$" "Does this match"
==>1
▪ Results:
The regular expression matches the string, so a 1 is
returned. The expression translates to: “Does the
searched string contain the word ‘does’ OR is ‘match’ the
last word of the string?”
64
regsub Command
▪ Syntax:
regsub exp string substitute
varName
▪ Description:
Copies string to varName.
While copying, if a match for exp is found, it is replaced
with substitute.
The number of substitutions is returned.
65
regsub Command
▪ Example:
regsub "match$" "match test - Does this match"
"**replaced**" sStr
==>1
puts $sStr
==> match test - Does this **replaced**
▪ Results:
The portion of the string that matched the regular expression is
replaced with another string, and the resulting string is placed in
the variable sStr. The number of substitutions is returned.
66
format Command
▪ Syntax:
format formatString ?value value …?
▪ Description:
Returns a string similar to formatString, except that % sequences
have been replaced by the given values.
▪ Example:
format "The %s number %d is %x in %s" \
decimal 23 23 hex
==>The decimal number 23 is 17 in hex
▪ Results:
A string is printed using the format defined
67
scan Command
▪ Syntax:
scan string format varName ?varName …?
▪ Description:
Parses the string according to the format and assigns values to
varName(s)
▪ Example:
scan "Decimal 23 = 17" "%s %d = %x" a b c
==>3
▪ Results:
Variable a=Decimal, b=23 and c=23. Returns number of scanned
items (3).
68
List processing
69
Lists
70
List Commands
71
list Command
▪ Syntax:
list ?value value …?
▪ Description:
Creates a list from the value arguments and returns it
▪ Example:
set lComps [list Memory Mouse “System Box”]
==>Memory Mouse {System Box}
▪ Results:
A list is created from the arguments and stored in the lComps variable
72
concat Command
▪ Syntax:
concat ?list list …?
▪ Description:
Concatenates multiple lists and returns the resulting list
▪ Example:
set lComps [concat $lComps [list Monitor Keyboard]]
==>Memory Mouse {System Box} Monitor Keyboard
▪ Results:
The lComps list is concatenated with the list of Monitor and Keyboard
to form a new list of Components
73
lappend Command
▪ Syntax:
lappend varName value ?value …?
▪ Description:
Appends all the values as a list to the list varName. **Creates
varname if it does not exist.
▪ Example:
lappend lComps Monitor
==> Memory Mouse {System Box} Monitor
▪ Results:
The Monitor is appended as a new item to lComps.
74
lindex Command
▪ Syntax:
lindex list index
▪ Description:
Returns the index item from the list varName (0 is the first item)
▪ Example:
lindex $lComps 2
==>System Box
▪ Results:
The 3rd item (index 2) is returned from the lComps list
75
llength Command
▪ Syntax:
llength list
▪ Description:
Returns the number of items in the list
▪ Example:
llength $lComps
==>5
▪ Results:
Returns the number of items in the lComps list
76
lrange Command
▪ Syntax:
lrange list first last
▪ Description:
Returns the list of items first through last of the list
▪ Example:
lrange $lComps 0 2
==> Memory Mouse {System Box}
▪ Results:
Items 0 through 2 of lComps are returned
77
linsert Command
▪ Syntax:
linsert list index value ?value …?
▪ Description:
Returns a list consisting of the original list with all the values inserted as
list items before the indexed item
▪ Example:
linsert $lComps 2 RAM
==> Memory Mouse RAM {System Box} Monitor Keyboard
▪ Results:
The value RAM is inserted before item 2 in the lComps list
78
lreplace Command
▪ Syntax:
lreplace list first last ?value value …?
▪ Description:
Returns the list with items first through last of list replaced with values
▪ Example:
lreplace $lComps 3 3
==> Memory Mouse RAM Monitor Keyboard
▪ Results:
Item 3 of list lComps is replaced with nothing
79
lsearch Command
▪ Syntax:
lsearch ?-glob? ?-exact? ?-regexp?
list pattern
▪ Description:
Returns the index of the first item in list that matches pattern
according to the specified technique (-1 if there are no matches)
▪ Example:
lsearch -glob $lComps *r*
==>0
▪ Results:
Returns the index of the first item in list lComps that matches *r*,
which is Memory, item 0
Memory Mouse RAM Monitor Keyboard
80
lsort Command
▪ Syntax:
lsort ?options? list
▪ Description:
Sorts the list based on the specified options and returns it. Options
include -ascii, -integer, -real, -dictionary, -increasing, -
decreasing, -index x, -command cmd .
▪ Example:
lsort -ascii $lComps
==> Keyboard Memory Monitor Mouse RAM
▪ Results:
The lComps list is sorted and returned
81
split Command
▪ Syntax:
split string ?splitChars?
▪ Description:
Splits the string at each instance of splitChars and returns a list
▪ Example:
split [mql list group] \n
==> {HCC Corp} Sales Manufacturing
▪ Results:
The string is split at each instance of the newline character and the
resulting list is returned
82
join Command
▪ Syntax:
join list ?joinString?
▪ Description:
Concatenates all the list items placing joinString between them and
returns the resulting string
▪ Example:
join $lGroups “|”
==>HCC Corp|Sales|Manufacturing
▪ Results:
The list is concatenated placing | between each list item and the
resulting string is returned
83
Arrays
84
Arrays
85
Array Variables
▪ Example:
set aPerson(firstname) Tom
set aPerson(lastname) Jones
▪ Results:
The array aPerson is created. The “firstname” element is
created in the aPerson array and given the value “Tom”.
The “lastname” element is created in the aPerson array
and given the value “Jones”.
86
Array Variables
puts $aPerson(firstname)
=> Tom
87
Array Commands
array exists
array size
array names
array set
array get
88
array exists Command
▪ Syntax:
array exists arrayName
▪ Description:
Checks if an array exists
▪ Example:
array exists aPerson
==>1
▪ Results:
Returns 1 indicating the array variable exists
89
array size Command
▪ Syntax:
array size arrayName
▪ Description:
Returns the number of name-value pairs in the array
▪ Example:
array size aPerson
==>2
▪ Results:
The number of name-value pairs in the aPerson array is returned
90
array names Command
▪ Syntax:
array names arrayName
▪ Description:
Returns each name in the array
▪ Example:
array names aPerson
==>firstname lastname
▪ Results:
The names in the array aPerson are returned
91
array set Command
▪ Syntax:
array set arrayName list
▪ Description:
Creates an array named arrayName from the elements in the list
▪ Example:
array set aPerson {name Joe job Boss}
▪ Results:
Creates array aPerson and associates name with Joe and job with
Boss
92
array get Command
▪ Syntax:
array get arrayName
▪ Description:
Returns each name-value pair in the array as list
▪ Example:
array get aPerson
==>name Joe job Boss
▪ Results:
The name-value pairs in the array aPerson are returned
93
env Array
puts $env(USERNAME)
==>smith
94
tcl_platform Array
▪ Example:
array get tcl_platform
==>byteOrder littleEndian osVersion 4.0 machine intel
platform windows os {Windows NT}
95
info Command
96
Control Flow
97
Control Flow Commands
98
if Command
▪ Syntax:
if test1 body1 ?elseif test2 body2
elseif …? ?else bodyn?
▪ Description:
If test1 evaluates to nonzero, then body1 is evaluated,
else if test2 evaluates to nonzero, then evaluate body2.
If none of the tests evaluate to nonzero, evaluate bodyn.
99
if Command
▪ Example: Note position of braces
if { $sPart == “Memory” } {
puts “Found Memory”
} elseif {$sPart == “Mouse”} {
puts “Found Mouse”
} else {
puts “Not Found”
}
▪ Results:
Print “Found Memory” if the sPart variable is set to
“Memory”, otherwise Print “Found Mouse” if the sPart
variable is set to “Mouse”, otherwise print “Not Found”
100
switch Command
▪ Syntax:
switch ?options? string {
value body
?default body …?
}
▪ Description:
Evaluates the body of the first value that matches
string. Options include -exact, -glob, -regexp.
101
switch Command
▪ Example:
switch -exact $sType {
Memory {mql print Type $sType }
“System Box” -
Microcomputer {mql delete Type $sType}
CustOrder {mql icon type $sType verbose}
default {puts “Undefined Type” }
}
▪ Results:
Matches the value of sType against the values and
evaluates the appropriate commands
102
for Command
▪ Syntax:
for init test reinit body
▪ Description:
Evaluates init Tcl command(s) to establish starting
values. The test expression is then evaluated. While
the expression is non-zero, the body command(s) are
executed. The reinit command(s) are evaluated at
the end of each loop cycle.
103
for Command
▪ Example:
for {set iNum 0} {$iNum<3} {incr iNum} {
puts $iNum
}
=> 0
1
2
▪ Results:
The loop is executed 3 times printing out 0, 1, and 2.
104
while Command
▪ Syntax:
while test body
▪ Description:
Evaluates body as a Tcl script while test evaluates to nonzero
▪ Example:
while { $iNum < 10 } { incr iNum }
▪ Results:
While iNum is less than 10, evaluate the body of the command
105
foreach Command
▪ Syntax:
foreach varName list body
▪ Description:
For each item in list, varName is set to the value of that item and
body is evaluated as a Tcl script
▪ Example:
foreach sRole [split [mql list role] \n] {
puts \
[mql print role $sRole select name person dump]
}
▪ Results: Prints out each role and persons in each role
Demo
Demo
106
break Command
▪ Syntax:
break
▪ Description:
Terminates the innermost nested looping command
▪ Example:
while { … } { break }
▪ Results:
If the break command is reached, then the while command is
terminated
107
continue Command
▪ Syntax:
continue
▪ Description:
Stops the current iteration of the innermost nested looping
command and goes to the next iteration
▪ Example:
while { … } { continue }
▪ Results:
If the continue command is reached, then control resumes at the
while command
108
eval Command
▪ Syntax:
eval arg ?arg arg …?
▪ Description:
Concatenates all the args separated by spaces and then
evaluates the resulting command
▪ Example:
set sType “Monitor”
set cmd {mql print bus $sType select policy}
eval $cmd
==>Production
109
source Command
▪ Syntax:
source filename
▪ Description:
Reads and evaluates all the commands in file filename
▪ Example:
source file.tcl
▪ Results:
Reads Tcl commands from the file and executes them
110
Error Handling
111
Exceptions
112
catch Command
▪ Syntax:
catch command ?varName?
▪ Description:
The command is executed and any exceptions are caught
The return from the catch command is a code indicating whether
the command caused an exception
If there was an exception, the error message is placed in
varName
113
catch Command
▪ Example:
catch { mql print type Mousx } sMessage
==>1
puts $sMessage
==>Error: #1900068: print type failed
System Error: #1500178: business type ’Mousx' does not
exist
▪ Results:
The command fails and is caught by the catch command. The
catch command returns a value of 1 (error) and sets the message
variable to the error message
114
errorCode and errorInfo
115
error Command
▪ Syntax:
error message ?info? ?code?
▪ Description:
Generates an error with the specified error message, aborts the
current Tcl script, and places info into the errorInfo variable and
code into the errorCode variable
▪ Example:
error “Program has caused an error to occur”
▪ Results:
An error is generated, the error message is displayed, and the Tcl
script is aborted
116
Procedures
117
Overview
118
Procedures
119
Procedure Commands
120
proc Command
▪ Syntax:
proc name argList body
▪ Description:
Creates or replaces a procedure called name, with a list of
arguments (argList) and the Tcl script to evaluate when the
procedure is called (body)
▪ Example:
proc pMyprint { sText } { puts $sText }
▪ Results:
Creates a procedure called pMyprint that prints out the
value of its argument
121
proc Default Arguments
122
proc Variable Arguments
123
Calling a Procedure
▪ Examples:
pGetPersonsFromRole Sales
pNotify “Meeting” “Room B - 2:00 PM” Ni Joe
pAddOrder CustomerOrder X23221 1
124
return Command
▪ Syntax:
return ?value?
▪ Description:
Used to return a value from a procedure
▪ Example:
proc getPersonsFromRole { sRole } {
set lPersons \
[mql print role $sRole select person dump]
return $lPersons
}
▪ Results:
The procedure returns a list of persons for a role
125
Variable Scope
▪ Local variables
Variables used within a procedure
Deleted when procedure returns
▪ Global variables
Variables used outside of a procedure
Deleted when a Tcl session exits
126
Variable Scope
proc getListLength { sList } {
set iPersons [llength $sList]
return $iPersons
}
set iPersons 0
getListLength “Joe Mary Ni”
==>3
puts $iPersons
==>0
Local variable iPersons is deleted when procedure ends
127
global Command
▪ Syntax:
global varName1 ?varName2 …?
▪ Description:
Causes the varNames to reference global variable of that same
name, instead of local variables
▪ Example:
global iPersons
▪ Results:
Any reference to iPersons within this procedure will access the
global variable iPersons
128
global Command
proc getListLength { sList } {
global iPersons
set iPersons [llength $sList]
return $iPersons
}
set iPersons 0
getListLength “Joe Mary Ni”
==>3
puts $iPersons
==>3
To access a global variable in a procedure use the
global command
129
upvar Command
▪ Syntax:
upvar sVarName1 myVarName1
?sVarName2 myVarName2 …?
▪ Description:
Provides a call by reference mechanism for a procedure.
The name of a variable is passed to a procedure rather
than the value. Most often used to pass entire arrays to a
procedure.
130
upvar Command
set Memory(RAM) 100
set Memory(Price) 100
▪ Results:
An array named Memory is declared and set with two indices
The PrintArrayElement procedure is called passing the Array and Element to display.
The “upvar” command makes the array passed in aArrayVar to be accessible as a
local variable aLocalArray
131
Using Procedures in Matrix
▪ A procedure must be declared within the same scope as
the currently executing MQL/Tcl program
▪ Once the procedure has been declared it can be used
within the main program
tcl;
eval {
proc pGetAttr {sType} {
return [mql print Type $sType \
select attribute dump |]
}
###############MAIN PROGRAM###############
set sAttr [pGetAttr “Monitor”]
}
132
Using Procedures in Matrix
▪ To reuse procedures create a program object procedure
“library”
▪ To use procedure “libraries” use a loader program with the
Tcl eval statement:
tcl;
eval {
proc pLoad {sProgram} {
return [mql print program $sProgram \
select code dump]
}
eval [pLoad MyProcedures]
eval [pLoad MyLibrary]
#############MAIN PROGRAM##############
set sList [pMyProcedure_GetRoles]
} 133
Files
134
Files
135
File Access Commands
▪ File Operations ▪ Directory Operations
open glob
gets pwd
read cd
eof
seek
tell
puts
flush
close
file
136
open Command
▪ Syntax:
open fileName ?access?
▪ Description:
Opens file fileName with mode access, default is read.
▪ Example:
set fInput [open “file.tcl” r]
==>file64
▪ Results:
The file is opened for read access and returns a file id
137
gets Command
▪ Syntax:
gets fileId ?varName?
▪ Description:
Reads the next line from fileId, discards the newline
▪ Example:
gets $fInput sText
==>15
▪ Results:
Reads a line of text (15 bytes) from file fInput into sText
138
read Command
▪ Syntax:
read fileId numBytes
▪ Description:
Reads and returns the next numBytes bytes of data in fileId
▪ Example:
read $fInput 50
==>(50 bytes of data from the file)
▪ Results:
50 bytes of data from the file is read and returned
139
read Command
▪ Syntax:
read ?-nonewline? fileId
▪ Description:
Reads and returns the rest of the data in fileId, disregarding the
final newline if -nonewline is specified
▪ Example:
read $fInput
==>(all the rest of the data in the file)
▪ Results:
All the rest of the data in the file is read and returned
140
eof Command
▪ Syntax:
eof fileId
▪ Description:
Returns 1 if fileId is at the end of file, otherwise returns 0
▪ Example:
eof $fInput
==>1
▪ Results:
The file is at the end, so a 1 is returned
141
tell Command
▪ Syntax:
tell fileId
▪ Description:
Returns the current access position for fileId
▪ Example:
tell $fInput
==>199
▪ Results:
The current access position is at byte 199
142
seek Command
▪ Syntax:
seek fileId offset ?origin?
▪ Description:
Sets the access position within fileId to be offset bytes from origin.
Origin may be start, current, or end, and defaults to start.
▪ Example:
seek $fInput 50 start
▪ Results:
The file access position is set to 50 and an empty string is
returned
143
puts Command
▪ Syntax:
puts ?-nonewline? ?fileId? string
▪ Description:
Writes a string to file Id (standard out by default) and appends a
newline character, unless -nonewline is specified
▪ Example:
puts $fOutput “This is a test”
▪ Results:
Writes the string to the file id and returns an empty string
144
flush Command
▪ Syntax:
flush fileId
▪ Description:
Writes out any buffered output for this file
▪ Example:
flush $fOutput
▪ Results:
The file buffer is flushed
145
close Command
▪ Syntax:
close fileId
▪ Description:
Closes the file designated by fileId
▪ Example:
close $fInput
▪ Results:
Closes the file
146
file Command
file atime file owned
file copy file pathtype
file delete file readable
file dirname file readlink
file executable file rename
file exists file rootname
file extension file size
file isdirectory file split
file isfile file stat
file join file tail
file lstat file type
file mkdir file writable
file mtime
147
file stat Command
▪ Syntax:
file stat fileName arrayName
▪ Description:
Sets items of arrayName to hold information about the fileName file
▪ Example:
file stat file.tcl aFileInfo
array get aFileInfo
==>mtime 853450007 atime 853945190 gid 0
nlink 1 mode -32320 type file
ctime 853450007 uid 0 ino 0
size 21932 dev 2
▪ Results:
The information about file.tcl is stored in aFileInfo
▪ Note - to format time:
clock format timevalue
148
Directory Operations
149
Processes
150
Processes
151
exec Command
▪ Syntax:
exec arg ?arg …?
▪ Description:
Combines all the arguments into one command and executes it in
the operating system
If the last argument is an ampersand (&), the command is
executed in the background. Otherwise, Tcl waits for the
command to finish.
All output is returned from the command
Exec supports I/O redirection.
▪ Example:
exec notepad &
==>246
▪ Results:
Executes notepad in the background and returns the process id
152
exit Command
▪ Syntax:
exit ?code?
▪ Description:
Exits the process and returns code (default 0) to the parent
▪ Example:
exit
▪ Results:
The process exits with return code 0
153
Summary
At the end of this session, you would have understood various
capabilities of TCL
▪ Commands/syntax
▪ Variables – Accessing variables, substitution
▪ Using MQL
▪ Grouping
▪ Writing comments
▪ Expressions
▪ Processing strings and lists
▪ Working with arrays
▪ Control flow – if, switch, for, while, foreach
▪ Error handling
▪ Procedures
▪ File processing
154
“Slice and Dice” technique
using Tcl split and foreach
155
Get data
1|Assembly|to|RAM Module|HP 4 Meg|A\n
from 1|Assembly|to|Floppy Disk|NEC 1.4|A\n
Matrix 1|Assembly|to|Hard Disk|Maxtor 1G|A\n
156
“Slice”
rows into
a list
{1|Assembly|to|RAM Module|HP 4 Meg|A}
{1|Assembly|to|Floppy Disk|NEC 1.4|A}
{1|Assembly|to|Hard Disk|Maxtor 1G|A}
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
157
Capture
each
element..
158
“Dice”
the
element
into a list
159
Capture
each list
element
160
Capture
each list
element
161
Capture
each list
element
162
Captured
data is
now
used...
163
foreach
now gets
the next
row...
164
“Dice” it
165
…and all
rows will
be
processed
166
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
NEC 1.4
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
167
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex
A $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
168
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
Floppy Disk NEC 1.4 A
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
169
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse 1|Assembly|to|Floppy
to all dump |]Disk|NEC 1.4|A
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
170
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split1 Assembly
$sCompsto \n]
{Hard Disk} {Maxtor 1G} A
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
171
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
Hard Disk
172
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
Maxtor 1G
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
173
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex
A $lsFields 3]
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
174
set sComps [mql expand bus “System Box” “Wiz Bang” A \
from recurse to all dump |]
set lsComps [split $sComps \n]
foreach sAssembly $lsComps {
set lsFields [split $sAssembly |]
set sType [lindex $lsFields 3]
Hard Disk Maxtor 1G A
set sName [lindex $lsFields 4]
set sRev [lindex $lsFields 5]
mql print bus $sType $sName $sRev
}
175
…until
the end
of the
list.
176