P. 1
Advanced TcL 1 Day Course Instructors Slides

Advanced TcL 1 Day Course Instructors Slides

|Views: 36|Likes:
An instructors presentation tool for the Advanced one-day Tcl course detailed in the corresponding Scribd Advanced Course PDF. Complete course slides, often with summarized topics, are included. Advanced Course and mastery of Tcl is assumed.
An instructors presentation tool for the Advanced one-day Tcl course detailed in the corresponding Scribd Advanced Course PDF. Complete course slides, often with summarized topics, are included. Advanced Course and mastery of Tcl is assumed.

More info:

Categories:Types, Research
Published by: John Michael Williams on Feb 11, 2013
Copyright:Traditional Copyright: All rights reserved
List Price: $10.00 Buy Now

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
See more
See less

02/23/2014

$10.00

USD

pdf

Sections

  • Course Organization
  • Introduction and Scope
  • Today's Agenda
  • Topics
  • Schedule
  • References and Online Help
  • What is a "Script"?
  • Script Languages
  • TcL Language Properties (Review)
  • Strings
  • String: A Vector of Characters
  • String Reading Command List
  • String Reading Commands I
  • string length Example:
  • String Reading Commands II
  • Regular expression basics
  • String Reading Commands III
  • String Reading Commands IV
  • String Reading Commands V
  • String Reading Commands VI
  • String Reading Commands VII
  • Example: Reading a Shopping List
  • Shopping List Code
  • String Reading Commands VIII
  • Quoting Problems
  • String Writing Command List
  • String Writing Commands I
  • String Writing Commands II
  • String Writing Commands III
  • String Writing Commands IV
  • String Writing Commands V
  • String Writing Commands VI
  • Lists
  • List: A Vector of String Words
  • List: Determining the Number of Words
  • List Writing Commands
  • List Writing Hierarchy I
  • List Writing Hierarchy II
  • List Writing Commands: split I
  • List Writing Commands: split II
  • List Writing Commands II
  • List Writing Commands III
  • List Reading Commands
  • Arrays
  • Array: A Set of 2-Word Lists
  • Array String-Access Commands
  • Array Access Commands
  • Array Info Commands I
  • Array Info Commands II
  • Array Iterator Commands
  • TcL and the Operating System
  • OS Identification
  • OS Environment Access
  • Error Handling: The catch Command
  • Error Handling: Safe File I/O
  • OS-Access Commands I
  • OS-Access Commands II
  • Advanced File I/O: read
  • Advanced File I/O: seek & tell
  • file: Data Access Commands
  • file: Data Access I
  • file: Data Access II
  • file: Context and Name Commands
  • file: File Access Commands
  • The TcL Interpreter
  • TcL info Command
  • Scripting and Debugging
  • Script Guidelines: General
  • Script Guidelines: Big Stuff
  • Script Debugging Rules
  • Adding Debugging Messages
  • Special Debugging Commands
  • Lab 1 Preface
  • Lab 1: Goals
  • Lab 1: Design Schematic
  • Lab 1: Verilog "Net-List" Example
  • Lab 1: Verilog Netlist Basics
  • Lab 1: Verilog Example Module: Multicounter
  • Lab 1: Verilog Instantiation Syntax
  • Lab 1: Netlist Modification
  • Multidimensional Arrays
  • TcL exec of OS Commands
  • OS Coordination: exec Backgrounding
  • OS Coordination: execing portably
  • TcL namespace
  • Applicability of namespace
  • Declaration and Hierarchy of Namespaces
  • Namespace Reliability
  • Namespace Commands I
  • namespace import Examples
  • Namespace Commands II
  • namespace code Command
  • The variable Command I
  • The variable Command II
  • The variable Command III
  • The rename Command
  • The uplevel Command
  • Namespace Safety Summary
  • Lab 2: OS exec; namespace
  • TcL Miscellaneous Topics
  • EDA Applications
  • SDC: An EDA Enhancement of TcL
  • Packages
  • Enhancements Beyond TcL
  • Review and Wrap-Up
  • Quick Review
  • That's It

Slides for

Advanced Script Writing in TcL
A Si l i con Val l ey Pol ytechni c I nsti tute Workshop
by J ohn Michael Williams
2013-01-09
Copyright © 2008, J ohn Michael Williams.
Licensed free to Silicon Valley Polytechnic Institute for training-course use.
All other rights reserved.
jmmwill@comcast.net
2010-05-16 TcL Advanced Scri pt Workshop
List of Slides
Course Organization.................................................................................................................................................................................................1
I ntroduction and Scope.............................................................................................................................................................................................2
Today's Agenda ....................................................................................................................................................................................................3
Topi cs ....................................................................................................................................................................................................................3
Schedul e................................................................................................................................................................................................................3
References and Onl i ne Hel p................................................................................................................................................................................4
What i s a "Scri pt"? ...............................................................................................................................................................................................5
Scri pt Languages .................................................................................................................................................................................................6
TcL Language Properti es (Revi ew).....................................................................................................................................................................7
Strings........................................................................................................................................................................................................................8
Stri ng: A Vector of Characters ...........................................................................................................................................................................9
Stri ng Readi ng Command Li st..........................................................................................................................................................................10
Stri ng Readi ng Commands I .............................................................................................................................................................................11
stri ng l ength Exampl e: ......................................................................................................................................................................................12
Stri ng Readi ng Commands I I ............................................................................................................................................................................13
Regul ar expressi on basi cs..................................................................................................................................................................................14
Stri ng Readi ng Commands I I I ..........................................................................................................................................................................15
Stri ng Readi ng Commands I V ..........................................................................................................................................................................16
Stri ng Readi ng Commands V............................................................................................................................................................................17
Stri ng Readi ng Commands VI ..........................................................................................................................................................................18
Stri ng Readi ng Commands VI I .........................................................................................................................................................................19
Exampl e: Readi ng a Shoppi ng Li st..................................................................................................................................................................20
Shoppi ng Li st Code ............................................................................................................................................................................................21
Stri ng Readi ng Commands VI I I .......................................................................................................................................................................22
Quoti ng Probl ems ..............................................................................................................................................................................................23
Stri ng Wri ti ng Command Li st ..........................................................................................................................................................................24
Stri ng Wri ti ng Commands I ..............................................................................................................................................................................25
Stri ng Wri ti ng Commands I I ............................................................................................................................................................................26
Stri ng Wri ti ng Commands I I I ...........................................................................................................................................................................27
Stri ng Wri ti ng Commands I V ...........................................................................................................................................................................28
Stri ng Wri ti ng Commands V.............................................................................................................................................................................29
Stri ng Wri ti ng Commands VI ...........................................................................................................................................................................30
Lists..........................................................................................................................................................................................................................31
2010-05-16 TcL Advanced Scri pt Workshop
Li st: A Vector of Stri ng Words .........................................................................................................................................................................32
Li st: Determi ni ng the Number of Words .........................................................................................................................................................33
Li st Wri ti ng Commands ....................................................................................................................................................................................34
Li st Wri ti ng Hi erarchy I ....................................................................................................................................................................................35
Li st Wri ti ng Hi erarchy I I ..................................................................................................................................................................................36
Li st Wri ti ng Commands: spl i t I .......................................................................................................................................................................37
Li st Wri ti ng Commands: spl i t I I ......................................................................................................................................................................38
Li st Wri ti ng Commands I I ................................................................................................................................................................................39
Li st Wri ti ng Commands I I I ...............................................................................................................................................................................40
Li st Readi ng Commands ...................................................................................................................................................................................41
Arrays.......................................................................................................................................................................................................................42
Array: A Set of 2-Word Li sts ............................................................................................................................................................................43
Array Stri ng-Access Commands .......................................................................................................................................................................44
Array Access Commands ...................................................................................................................................................................................45
Array I nfo Commands I .....................................................................................................................................................................................46
Array I nfo Commands I I ...................................................................................................................................................................................47
Array I terator Commands .................................................................................................................................................................................48
TcL and the Operating System...............................................................................................................................................................................49
OS I denti fi cati on ................................................................................................................................................................................................50
OS Envi ronment Access ....................................................................................................................................................................................51
Error Handl i ng: The catch Command .............................................................................................................................................................52
Error Handl i ng: Safe Fi l e I /O...........................................................................................................................................................................53
OS-Access Commands I .....................................................................................................................................................................................54
OS-Access Commands I I ....................................................................................................................................................................................55
Advanced Fi l e I /O: read ...................................................................................................................................................................................56
Advanced Fi l e I /O: seek & tel l .........................................................................................................................................................................57
fi l e: Data Access Commands ............................................................................................................................................................................58
fi l e: Data Access I ..............................................................................................................................................................................................59
fi l e: Data Access I I ............................................................................................................................................................................................60
fi l e: Context and Name Commands .................................................................................................................................................................61
fi l e: Fi l e Access Commands ..............................................................................................................................................................................62
The TcL I nterpreter ...........................................................................................................................................................................................63
TcL i nfo Command.............................................................................................................................................................................................64
Scripting and Debugging........................................................................................................................................................................................65
Scri pt Gui del i nes: General ...............................................................................................................................................................................66
Scri pt Gui del i nes: Bi g Stuff..............................................................................................................................................................................67
Scri pt Debuggi ng Rul es .....................................................................................................................................................................................68
Addi ng Debuggi ng Messages.............................................................................................................................................................................69
2010-05-16 TcL Advanced Scri pt Workshop
Speci al Debuggi ng Commands..........................................................................................................................................................................70
Lab 1 Preface...........................................................................................................................................................................................................71
Lab 1: Goal s .......................................................................................................................................................................................................72
Lab 1: Desi gn Schemati c ..................................................................................................................................................................................73
Lab 1: Veri l og "Net-Li st" Exampl e...................................................................................................................................................................74
Lab 1: Veri l og Netl i st Basi cs ............................................................................................................................................................................75
Lab 1: Veri l og Exampl e Modul e: Mul ti counter ..............................................................................................................................................76
Lab 1: Veri l og I nstanti ati on Syntax ................................................................................................................................................................77
Lab 1: Netlist Modification....................................................................................................................................................................................78
Mul ti di mensi onal Arrays...................................................................................................................................................................................79
TcL exec of OS Commands.....................................................................................................................................................................................80
OS Coordi nati on: exec Backgroundi ng............................................................................................................................................................81
OS Coordi nati on: execi ng portabl y ..................................................................................................................................................................82
TcL namespace ........................................................................................................................................................................................................83
Appl i cabi l i ty of namespace................................................................................................................................................................................84
Decl arati on and Hi erarchy of Namespaces ......................................................................................................................................................85
Namespace Rel i abi l i ty .......................................................................................................................................................................................86
Namespace Commands I ...................................................................................................................................................................................87
namespace i mport Exampl es.............................................................................................................................................................................88
Namespace Commands I I ..................................................................................................................................................................................89
namespace code Command................................................................................................................................................................................90
The vari abl e Command I ...................................................................................................................................................................................91
The vari abl e Command I I .................................................................................................................................................................................92
The vari abl e Command I I I ................................................................................................................................................................................93
The rename Command ......................................................................................................................................................................................94
The upl evel Command .......................................................................................................................................................................................95
Namespace Safety Summary ............................................................................................................................................................................96
Lab 2: OS exec; namespace...................................................................................................................................................................................97
TcL Miscellaneous Topics.......................................................................................................................................................................................98
EDA Appl i cati ons ...............................................................................................................................................................................................99
SDC: An EDA Enhancement of TcL ..............................................................................................................................................................100
Packages ...........................................................................................................................................................................................................101
Enhancements Beyond TcL.............................................................................................................................................................................102
Review and Wrap-Up............................................................................................................................................................................................103
Qui ck Revi ew....................................................................................................................................................................................................104
That's I t .................................................................................................................................................................................................................105
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 1
Course Organi zati on
The course consi sts of l ecture and two l abs.
Breaks wi l l be schedul ed about every hour duri ng l ecture.
• Pl ease take a break any ti me duri ng l ab.
• Pl ease i nterrupt l ecture i f you become l ost or confused. Pl ease
save el aborati ve or compl ex questi ons for l ab ti me.
Pl ease don't operate portabl e computers, i ncl udi ng cel l phones, duri ng
l ecture. Turn them off and use them duri ng break; or, i f unavoi dabl e, duri ng
l ab ti me.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 2
I ntroducti on and Scope
This a course in script-writing:
I t i ncl udes:
• background on scri pti ng l anguages
• detai l s on commands to mani pul ate stri ngs, l i sts, and arrays
• advanced fi l e I /O and error-handl i ng
• envi ronment and other OS-rel ated features
• debuggi ng tacti cs
• namespace usage.
I t does not i ncl ude:
⊗ exerci se of basi c TcL (take the TcL Fundamentals course)
⊗ anythi ng graphi cal
⊗ anythi ng speci fi c to graphi cal programmi ng:
concurrency, cal l backs, process control
⊗ anythi ng requi ri ng a TcL extensi on (expect; incr TcL; Tk; etc.).
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 3
Today's Agenda
Topi cs
Words Actions More Words
Implementation Lecture
Stri ng, Li st, Array Commands
OS I nterface & Envi ronment
Error-Handl i ng
Advanced fi l e I /O
Generalities
Gui del i nes
Debuggi ng
Lab 1: Scripting Project
TcL-Shel l Coordi nati on
namespaces
Lab 2: Shell and namespace
Wrap-up Lecture
TclX,
Tk and wish
packages
C I nterfaces
TcL i n EDA; SDC
Schedul e
Time Topic
9:00 - 10:00
Stri ngs and Li sts
10:00 - 11:00
Arrays; Envi ronment
11:00 - 12:00
Fi l e I /O; System Access
12:00 - 12:30
Lunch (provi ded)
12:30 - 12:45
Scri pti ng Gui del i nes
12:45 - 15:00
Lab 1: Netl i st Project
15:00 - 16:00
Namespaces; shel l coordi nati on
16:00 - 17:00
Lab 2: Namespaces; exec
17:00 - 17:30
Beyond TcL Shel l ; Wrap-up
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 4
References and Onl i ne Hel p
References
Anonymous. ActiveTcl User Guide. http://www.activestate.com (2005-12-24).
Anonymous. TcL Developer Exchange. http://www.tcl.tk/ (2006-06-06). I f you
are i nterested i n object-ori entati on, see http://www.tcl.tk/about/oo.html.
Fl ynt, Cl i f. TclTutor. I nteracti ve tutori al ; good revi ew of basi cs. Avai l abl e onl i ne or
for downl oad at http://www.msen.com/~clif/Tcl.html (2006-06-09).
Johnson, Ray. Tcl Style Guide. Sun Mi crosystems, ca. 1997. Especi al l y val uabl e for
tk programs or mul ti pl e-fi l e programs l arger than scri pts.
http://www.tcl.tk/doc/styleGuide.pdf (2006-06-30).
Wel ch, Brent B., Jones, Ken, and Hobbs, Jeffrey. Practical Programming in Tcl/ Tk.
Upper Saddl e Ri ver, New Jersey: Prenti ce-Hal l , 2003.
Wi l l i son, S. A (re)I ntroduction to J avascript. http://simonwillison.net (2006-04-
09).
Help
TcL from ActiveState comes wi th an onl i ne, i ntegrated hel p system.
I n Wi ndows, thi s i s i n a Wi ndows Hel p format fi l e.
I n Li nux or Uni x, the TcL manual page di rectory may be added to the $MANPATH;
then, one may use the man command to request hel p on any speci fi c command
or topi c. TcL i s secti on n; use man n topi c
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 5
What i s a "Scri pt"?
Uses other executabl es to do i ts work.
Smal l er i n l i ne-count than the usual compi l ed program.
Usual l y resi des i n one di sc fi l e.
General l y wri tten and mai ntai ned by one person.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 6
Scri pt Languages
shell scripts
Uni x or Li nux: sh, bash, csh, tcsh.
batch fi l es (DOS); job-control decks
awk
Uni x or Li nux; has been ported to DOS.
javascript
HTML browser
perl
Al l common OS's. Si mi l ar scope to TcL; syntax cl oser to C.
TcL
Al l common OS's. Easi er to port than perl, but fewer system cal l s.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 7
TcL Language Properti es (Revi ew)
• TcL i s an i nterpreted l anguage; no compi l er.
• Not one reserved word. set, puts, etc., redefi nabl e.
• Al l statements are one l i ne. Must escape or quote NL's.
• Standard procedures (procs) have l ower-case names, onl y.
• Fi rst word i n a statement al ways i s a command i denti fi er (so,
unfortunatel y, one must set a vari abl e).
• One-character bl ocki ng tokens: ", or { }. No wordy "begin", "end", etc.
• Decl ared names preferabl y are al phanumeri c: A-Z, a-z, _, and 0-9.
• Bl anks are separators.
• Statements = semi col ons. But, NL al so works, usual l y.
• One comment token: #. Li ne-comments, onl y.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 8
Stri ngs
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 9
Stri ng: A Vector of Characters
Characters, not bytes.
Any typeface representati on works.
Si ze i s determi ned by char count.
Uni code stri ng woul d occupy twi ce the computer memory as
ASCI I .
TcL i nterpreter doesn't care, except for two or three bi nary
commands.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 10
Stri ng Readi ng Command Li st
We shal l cover:
puts
string bytelength
string length
string compare
string equal
string match
regexp
scan
string index
string range
string first
string last
string wordend
string wordstart
string is
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 11
Stri ng Readi ng Commands I
puts
string bytelength. Not often used; bi nary.
string length. Very useful .
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 12
string length Exampl e:
proc countFirstAs { StringIn } \
{
set Acount 0;
set Max [expr [string length $StringIn]/2];
for {set i 0;} {$i<$Max} {set i [expr $i+1];} \
{ if {[string index $StringIn $i] eq "a"} \
{ set Acount [expr $Acount+1]; }
}
puts "The first half of the string,
\[$StringIn\]
has $Acount a's.";
}
#
set String "The quick brown fox";
set String "$String was faster than a dog but slower than a bullet.";
#
countFirstAs $String;
> The first half of the string, ↓ ↓↓ ↓
[The quick brown fox was faster than a dog but slower than a bullet.]
has 2 a's.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 13
Stri ng Readi ng Commands I I
string compare (sorti ng)
string equal (bool ean)
string match (al l ows glob)
set String "How could you miss that fox?";
set Pattern {*i[sl][ls] *};
if {[string match $Pattern $String]} \
{ set Ans "I don't know."; } \
else { set Ans "What fox?"; }
#
puts "$String\n$Ans";
> How could you miss that fox?
> I don't know.
Al so matches, "How could you kill that fox?".
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 14
Regul ar expressi on basi cs
Use glob (fi l ename wi l dcard) tokens, but wi th total l y di fferent meani ng.
Expessi on el ements are cal l ed atoms.
New atoms formed by parentheses.
One wi l dcard: . (dot; peri od)
Other chars are atom qual i fi ers: *, +, ?, etc.
Exampl es:
a = atom.
(ab) = atom.
(ab)|(cd) = 2 atoms ored.
((ab)|(cd)) = atom.
a* = anythi ng wi th zero or more a chars.
a? = anythi ng wi th zero or one a char.
a+ = anythi ng wi th an a.
[abcd]+ = exactl y one of a, b, c, or d.
a|(cd) = anythi ng contai ni ng an a or a cd.
^a|(cd)$ = ei ther "a" or "cd", and nothi ng el se.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 15
Stri ng Readi ng Commands I I I
regexp. Accepts -nocase, -all, and -start.
set Pat {(ab)|(cd)};
set String "another dopey example here."
regexp $Pat $String; # Returns 0: $String has neither "ab" nor "cd".
#
set Pat {a|(cd)};
regexp $Pat $String; # Returns 1 because $String has an 'a'.
set Pat {^[^abc].* +$};
set String [format "another dopey example here."]
regexp $Pat $String; # Returns 0: $String starts with 'a'.
#
set Pat { +$};
regexp $Pat $String; # Returns 0; last char not a blank.
#
set String "Another dopey example here. "
regexp $Pat $String; # Returns 1.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 16
Stri ng Readi ng Commands I V
scan. Li ke C sscanf: %d, %x, %s, %c; %i for i nteger; %u for unsi gned
i nteger; %e, %f, and %g for fl oati ng-poi nt numbers.
set String "The data are: 1000 51.5 abcklm and 0.051";
set ConvFmt {The data are: %i %f %s and %f}; # Notice the matches.
scan $String $ConvFmt Vi Vf1 Vs Vf2;
puts "Integer=$Vi Float1=$Vf1 String=$Vs Float2=$Vf2.";
> Integer=1000 Float1=51.5 String=abcklm Float2=0.051.
#
set ConvFmt {The data are: %i %s and %f};
scan $String $ConvFmt Vi Vf1 Vs Vf2;
> variable is not assigned by any conversion specifiers
#
# Avoid the error by scanning to a return value, not
# to variables:
set ResultList [scan $String $ConvFmt]
puts "Resulting list=\[$ResultList\].";
> Resulting list=[1000 51.5 {}].
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 17
Stri ng Readi ng Commands V
scan. To obtai n ASCI I char codes, use %c:
set Code [scan "a" %c]; # %c converts to octal code.
puts $Code;
> 97
set Code [format "0x%02x" $Code]; # %x converts value to hex code.
puts $Code;
> 0x61
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 18
Stri ng Readi ng Commands VI
string index
set String "One person's meat is anothers poison."
puts [string index $String 1]
> n
string range
set String "One person's meat is anothers poison."
puts "[string range $String 0 12] [string range $String 30 end].";
> One person's poison..
string first
set String "One person's meat is anothers poison."
puts "1st '=[string first {'} $String]; 1st o=[string first o $String]";
> 1st '=10; 1st o=8
#
puts "1st o after 11=[string first o $String 12]";
> 1st o after 11=23
string last
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 19
Stri ng Readi ng Commands VI I
string wordend
Returns the i ndex of the fi rst char fol l owi ng the word i n whi ch the provi ded
starti ng i ndex i s l ocated. A "word" i s one or more conti guous al phanumeri cs
(i ncl . '_'), onl y. Thus, i t l ocates the trai l i ng boundary of the current word. I f
the starti ng i ndex i s on an i sol ated char, i t returns the i ndex of the next char.
0 10 14
| | |
puts [string wordend 10 "This fox lives in a tree."];
> 14
string wordstart.
Returns the i ndex of the fi rst char i n the word contai ni ng the starti ng
i ndex. Thus, i t l ocates the start of the current word.
0 10
| |
puts [string wordstart 10 "This fox lives in a tree."];
> 9
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 20
Exampl e: Readi ng a Shoppi ng Li st
getItem() Desi gn:
We wi sh to extract the i tems from a shoppi ng l i st.
• The l i st i s del i mi ted by commas (l ast i tem by a peri od).
• There i s some i ntroductory text to el i mi nate. The i ntroductory text ends
wi th a col on (':').
• We want just a l i st
of i tem names,
each one
termi nated by a
semi col on.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 21
Shoppi ng Li st Code
proc getItem { Str } \
{set Len [string length $Str];
set i [string last {:} $Str];
# $i now indexes the ':'.
set WordIx [expr $i+1];
set ItemIx $WordIx;
while { $WordIx<$Len } \
{set WordEndIx [string wordend $Str $WordIx];
set WordEndChar [string index $Str $WordEndIx];
# Check the char at the end of the current word:
if { $WordEndChar eq {,} || $WordEndChar eq {.} } \
{
# Found an item delimiter; output everything since the last one:
set ItemEndIx [expr $WordEndIx-1];
puts -nonewline "[string range $Str $ItemIx $ItemEndIx]; ";
# Set the start of the next item:
set ItemIx [string wordstart $Str [expr $WordEndIx+2]];
}
# Update the start of the next word:
set WordIx $WordEndIx;
}
}
set String "Shopping List: celery, turkey slices, milk, eggs, bread.";
getItem $String;
> celery; turkey slices; milk; eggs; bread;
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 22
Stri ng Readi ng Commands VI I I
string is
Uses a set of predefi ned uni code categori es:
For exampl e, i f the stri ng $String i s enti rel y pri ntabl e,
string is graph $String wi l l return 1.
Other categori es:
alnum, alpha, ascii, boolean, control, digit, double, false,
integer, lower, print, punct, space, true, upper, wordchar, xdigit.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 23
Quoti ng Probl ems
When deal i ng wi th quoted substri ngs, remember:
• Quotes can not be nested; the outermost ones are the quotes.
• Strong quotes quote '\' and '"'.
• Strong quotes do not quote '{'.
• Weak quotes quote '{'.
• Weak quotes do not quote '"', '$', '[', or '\'.
Use strong quotes, i f possi bl e.
Exampl es:
Strong quotes:
set Str {We have a [, \{, and $; then, a \ and a word, "\slash"."};
puts $Str;
> We have a [, \{, and $; then, a \ and a word, "\slash"."
Weak quotes:
set Str "We have a \[, {, and \$; then, a \\ and a word, \"\\slash\".\"";
puts $Str;
> We have a [, {, and $; then, a \ and a word, "\slash"."
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 24
Stri ng Wri ti ng Command Li st
We shal l cover:
gets
expr
incr
subst
append
string repeat
format
string replace
string map
string toupper
string tolower
string totitle
string trim
string trimleft
string trimright
regsub
binary format
binary scan
encoding
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 25
Stri ng Wri ti ng Commands I
gets; expr; incr
subst
set x 3;
set y 7;
set Line { \Stmt_001: The sum of $x and $y is [expr $x+$y]};
#
puts [subst $Line];
> Stmt_001: The sum of 3 and 7 is 10
puts [subst -nobackslash $Line];
> \Stmt_001: The sum of 3 and 7 is 10
puts [subst -novariable $Line];
> Stmt_001: The sum of $x and $y is 10
append
set x "The quick brown";
set y "cookie";
set z "disappeared faster than a speeding bullet.";
append w $x { } $y { } $z;
puts $w;
> The quick brown cookie disappeared faster than a speeding bullet.
format
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 26
Stri ng Wri ti ng Commands I I
string replace
proc replaceRange { OldStr GuessIx NewStr } \
{
set Ix1 [string wordstart $OldStr $GuessIx];
set Ix2 [string wordend $OldStr $Ix1];
set Ix2 [expr $Ix2 - 1];
return [string replace $OldStr $Ix1 $Ix2 $NewStr];
}
#
set String "Your tooth was broken by a cookie?";
set NewString [replaceRange $String 6 {diet}];
puts $NewString;
> Your diet was broken by a cookie?
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 27
Stri ng Wri ti ng Commands I I I
string map
set String "Your tooth was broken by a cookie?";
puts [string map {tooth diet} $String];
> Your diet was broken by a cookie?
array set A [list]; # Force $A to be an array.
set A(tooth) "foot";
set A(cookie) "{300-kg fox}"; # string map will need braces.
#
set String "Your tooth was broken by a cookie?";
set Map "tooth $A(tooth) cookie $A(cookie)";
set NewString [string map "$Map" "$String"];
puts $NewString;
> Your foot was broken by a 300-kg fox?
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 28
Stri ng Wri ti ng Commands I V
string toupper; string tolower; string totitle
set String "oh. that fox."
puts [string totitle $String];
> Oh. that fox.
string trim; string trimleft; string trimright
set String "The wounded fox charged out of the underbrush.";
set Ix1 [string wordstart $String 12];
set Ix2 [string wordend $String 12];
set Word [string range $String $Ix1 $Ix2];
puts \[$Word\];
> [fox ]
set Word [string trim $Word];
puts \[$Word\];
> [fox]
set Word [string trim $Word {f}];
puts \[$Word\];
> [ox]
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 29
Stri ng Wri ti ng Commands V
regsub (same opti ons as regexp). Works l i ke sed:
set NewString "This is the old value.";
set String "The slow gray ox stepped on the lazy dog's foot."
regsub {.*step.*d } $String {We put a splint } NewString;
puts $NewString;
> We put a splint on the lazy dog's foot.
Use of posi ti onal references to reverse words:
set Str "The slow gray ox stepped on the lazy dog's foot."
set NewStr [regsub {(.*)(ox)(.*)(dog)(.*)} $Str {\1\4\3\2\5}];
puts $NewStr;
> The slow gray dog stepped on the lazy ox's foot.
binary format; binary scan
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 30
Stri ng Wri ti ng Commands VI
encoding names: Reports al l avai l abl e OS encodi ngs.
encoding names
> cp860 cp861 cp862 cp863 tis-620 cp864 cp865 cp866 gb12345
gb2312-raw cp949 cp950 cp869 dingbats ksc5601 macCentEuro
cp874 macUkraine jis0201 gb2312 euc-cn euc-jp macThai
iso8859-10 jis0208 iso2022-jp macIceland iso2022 iso8859-13
jis0212 iso8859-14 iso8859-15 cp737 iso8859-16 big5 euc-kr
macRomania macTurkish gb1988 iso2022-kr macGreek ascii cp437
macRoman iso8859-1 iso8859-2 iso8859-3 macCroatian koi8-r
iso8859-4 ebcdic iso8859-5 cp1250 macCyrillic iso8859-6
cp1251 macDingbats koi8-u iso8859-7 cp1252 iso8859-8 cp1253
iso8859-9 cp1254 cp1255 cp850 cp1256 cp932 identity cp1257
cp852 macJapan cp1258 shiftjis utf-8 cp855 cp936 symbol
cp775 unicode cp857
encoding convertfrom: Creates uni code.
encoding convertto: Creates newl y encoded chars from uni code.
encoding system: Reports current encodi ng; or, sets new encodi ng for
subsequent TcL i nterpreter commands.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 31
Li sts
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 32
Li st: A Vector of Stri ng Words
set List { {a b} {c {d e} f} g h };
Fi rst l evel of quoti ng consi sts of 4 substri ngs, {a b}, {c {d e} f},
g, and h. Li st commands wi l l operate on $List as a l i st of 4
el ements:
Word 0 Word 1 Word 2 Word 3
{a b} {c {d e} f} {g} {h}
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $List $i]\]"; }
#
> 0=[a b] 1=[c {d e} f] 2=[g] 3=[h] 4=[] 5=[] 6=[]
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 33
Li st: Determi ni ng the Number of Words
set L "a bc d ef"; # 4 words, quoted for correct set syntax.
puts $L;
> a bc d ef
set L [list a bc d ef]; # 4 words again, this time obviously.
puts $L;
> a bc d ef
#
# However, the list command counts words:
#
set LL [list $L]; # $L is 1 word, obviously.
puts $LL;
> {a bc d ef}
Thi s l ast resul t can be obtai ned by quoti ng al one:
set L "{a bc d ef}"; # 1 word, with braces quoted.
puts $L;
> {a bc d ef}
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 34
Li st Wri ti ng Commands
We shal l cover:
join
list
split
lset
lappend
linsert
lreplace
concat
lsort
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 35
Li st Wri ti ng Hi erarchy I
join, defaul t opti on fl attens a l i st:
set List { {a b} {c {d e} f} g h };
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $ListJ $i]\]"; }
> 0=[a b] 1=[c {d e} f] 2=[g] 3=[h] 4=[] 5=[] 6=[]
#
set ListJ [join $List];
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $ListJ $i]\]"; }
> 0=[a] 1=[b] 2=[c] 3=[d e] 4=[f] 5=[g] 6=[h]
#
set ListJJ [join $ListJ];
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $ListJJ $i]\]"; }
> 0=[a] 1=[b] 2=[c] 3=[d] 4=[e] 5=[f] 6=[g]
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 36
Li st Wri ti ng Hi erarchy I I
join, nondefaul t opti on joi ns l i st el ements:
set List { {a b} {c {d e} f} g h };
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $List $i]\]"; }
> 0=[a b] 1=[c {d e} f] 2=[g] 3=[h] 4=[] 5=[] 6=[]
#
set ListJ [join $List "_"]; # One underscore.
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $ListJ $i]\]"; }
> 0=[a] 1=[b_c] 2=[d e] 3=[f_g_h] 4=[] 5=[] 6=[]
#
set ListJJ [join $ListJ "__"]; # Two underscores.
for {set i 0;} {$i<=6} { set i [expr $i+1];} \
{ puts -nonewline " $i=\[[lindex $ListJJ $i]\]"; }
> 0=[a__b_c__d] 1=[e__f_g_h] 2=[] 3=[] 4=[] 5=[] 6=[]
Note that, unl i ke string trim and split, whi ch al so have opti ons, join
accepts a stri ng to use for joini ng, not a set of si ngl e chars.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 37
Li st Wri ti ng Commands: split I
Assume the fol l owi ng reporti ng proc and the fol l owi ng stri ng $String i n
the fol l owi ng exampl es:
proc reportList { List } \
{ set N 0;
foreach {Word} "$List" { puts -nonewline "$N=\[$Word\] "; incr N; }
puts "";
}
set String {{The {quick {brown {fox}}}} fell into {the {lazy {river}}} .}
Unmodi fi ed l i st:
reportList $String;
> 0=[The {quick {brown {fox}}}] 1=[fell] 2=[into] 3=[the {lazy {river}}]
4=[.]
To compare wi th split, here i s the l i st joined once:
set StrJoin [join $String];
reportList $StrJoin
> 0=[The] 1=[quick {brown {fox}}] 2=[fell] 3=[into] 4=[the] 5=[lazy
{river}] 6=[.]
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 38
Li st Wri ti ng Commands: split I I
The ori gi nal l i st split once, wi th no opti on, and reported:
set StrSplit [split $String];
reportList $StrSplit
> 0=[{The] 1=[{quick] 2=[{brown] 3=[{fox}}}}] 4=[fell] 5=[into] 6=[{the]
7=[{lazy] 8=[{river}}}] 9=[.]
The ori gi nal l i st split once, as i t appears di rectl y:
puts "split \$String=[split $String]";
> split $String=\{The \{quick \{brown \{fox\}\}\}\} fell into \{the
\{lazy \{river\}\}\} .
Here i t i s a split wi th a {Tt} set (=al ternati on) opti on:
puts "split \$String Tt=[split $String {Tt}]";
> split $String Tt=\{ he\ \{quick\ \{brown\ \{fox\}\}\}\}\ fell\ in o\ \{
he\ \{lazy\ \{river\}\}\}\ .
The 1-char l i st created by split wi th an empty-stri ng opti on:
puts "split \$String {}=[split $String {}]";
> split $String {}=\{ T h e { } \{ q u i c k { } \{ b r o w n { } \{ f o
x \} \} \} \} { } f e l l { } i n t o { } \{ t h e { } \{ l a z y { } \{
r i v e r \} \} \} { } .
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 39
Li st Wri ti ng Commands I I
lset
set List [list The "quick brown fox" came to the aid of the party.];
puts $List;
> The {quick brown fox} came to the aid of the party.
lset List 1 "party pooper";
puts $List;
> The {party pooper} came to the aid of the party.
lappend
lappend List The lazy "brown fox"; # Create it if it didn't exist.
puts $List;
> The lazy {brown fox}
lappend List never even tried to jump.;
puts $List;
> The lazy {brown fox} never even tried to jump.
linsert
set List [list The lazy "brown fox"];
set List [linsert $List 2 good-for-nothing];
puts $List;
> The lazy good-for-nothing {brown fox}
lreplace
set List [list The quick {brown fox} got away from the dogs.];
puts [lreplace $List 2 4 dogcatcher took the fox];
> The quick dogcatcher took the fox from the dogs.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 40
Li st Wri ti ng Commands I I I
concat. One of many ways to connect substri ngs:
set Str1 "{houses, gardens}, trees";
set Str2 "woods, lakes, clouds";
puts "$Str1, $Str2";
> {houses, gardens}, trees, woods, lakes, clouds
puts [concat $Str1 $Str2];
> {houses, gardens}, trees woods, lakes, clouds
puts [list $Str1 "," $Str2];
> {{houses, gardens}, trees} , {woods, lakes, clouds}
puts [join [list $Str1 $Str2] ", "];
> {houses, gardens}, trees, woods, lakes, clouds
puts [split "$Str1, $Str2"];
> \{houses, gardens\}, trees, woods, lakes, clouds
lsort
set List [list {Frank Ellen} {James Elisabeth} {Ernest Jane}];
puts [lsort $List];
> {Ernest Jane} {Frank Ellen} {James Elisabeth}
puts [lsort -index 1 $List];
> {James Elisabeth} {Frank Ellen} {Ernest Jane}
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 41
Li st Readi ng Commands
llength
set List [list a b cc def lex zed wet thr];
for {set i 0} {$i<[llength $List]} {incr i} \
{ puts -nonewline "$i=[lindex $List $i] "; }
> 0=a 1=b 2=cc 3=def 4=lex 5=zed 6=wet 7=thr
lrange
set List [list a b cc def lex zed wet thr];
puts [lrange $List 6 end];
> wet thr
lsearch. Accepts -start; pattern opti ons -glob, -regexp, or -exact.
set List [list a eb cc def lex zed wet def thr def {} { }];
puts [lsearch -all -glob $List {?e*}];
> 3 4 5 6 7 9
set Lfound [lsearch -all -inline -glob $List {?e*}];
puts $Lfound;
> def lex zed wet def def
puts [lsort -unique $Lfound];
> def lex wet zed
lindex
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 42
Arrays
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 43
Array: A Set of 2-Word Li sts
Li sts are n-word vectors.
A l i st wi th an even number of words can be converted to an array.
Array format:
{ {name} {val ue} } # 2-word vector
{ {name} {val ue} } # 2-word vector
... ...
{ {name} {val ue} } # 2-word vector
The vectors are unordered i n the array.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 44
Array Stri ng-Access Commands
Stri ng access commands use name associ ati on to the
value stored:
→ express a val ue by $Array(name)
→ assi gn a val ue by Array(name)
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 45
Array Access Commands
array set; array get; array names
set Alist "a {a value} b {b value} 1 {1 value}";
array set Array $Alist;
puts "names=\[[array names Array]\]";
> names=[1 a b]
#
puts "b=\[[array get Array b]\]";
> b=[b {b value}]
#
array set Array [list b "new b value"];
puts "b=\[[array get Array b]\]";
> b=[b {new b value}]
puts [array get Array];
> a {a value} b {new b value} 1 {1 value}
array unset
array set Array [list a {a value} abc {abc value} ab1 {ab1 value}];
array unset Array a*;
puts "\[[array names Array]\]";
> names=[]
puts "\[[array exists Array]\]"; # We now have an empty $Array:
> [1]
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 46
Array I nfo Commands I
array exists; array size
array set A [list];
puts "names=\[[array names A]\]";
> names=[]
puts array exists A;
> 1
puts [array size A];
> 0
set A 1;
> can't set "A": variable is array
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 47
Array I nfo Commands I I
array statistics
array set Array [list a {a value} abc {abc value} ab1 {ab1 value}];
array statistics Array
3 entries in table, 4 buckets
number of buckets with 0 entries: 1
number of buckets with 1 entries: 3
number of buckets with 2 entries: 0
number of buckets with 3 entries: 0
... (other 0's omitted) ...
number of buckets with 10 or more entries: 0
average search distance for entry: 1.0
The hash i s bui l t on the el ement names:
array set Array [list a {a value} abc {abc value} ac1 {ab1 value}];
array statistics Array
3 entries in table, 4 buckets
number of buckets with 0 entries: 2
number of buckets with 1 entries: 1
number of buckets with 2 entries: 1
number of buckets with 3 entries: 0
... (other 0's omitted) ...
number of buckets with 10 or more entries: 0
average search distance for entry: 1.3
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 48
Array I terator Commands
array startsearch; array nextelement; array anymore;
array donesearch
proc searchArray { Ary } \
{upvar $Ary AryL; # *L = local link.
set N 0;
set A [array startsearch AryL];
while {[array anymore AryL $A]} \
{
set Name [array nextelement AryL $A];
set Value $AryL($Name);
lappend ResultList "$N: $Name->$Value";
set N [expr $N+1];
}
array donesearch AryL $A;
return $ResultList;
}
array set Array [list a 41 b 42 c x01 1 rt 4 a4];
puts "names=[array names Array].";
> names=4 1 a b c.
puts "search=[searchArray Array].";
> search={0: 4->a4} {1: 1->rt} {2: a->41} {3: b->42} {4: c->x01}.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 49
TcL and the Operati ng System
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 50
OS I denti fi cati on
Use the $tcl_platform array.
Typi cal (Li nux) el ements:
osVersion 2.6.11-1.1369_FC4 platform unix
byteOrder littleEndian os Linux
threaded 1 user jmw
machine i586 wordSize 4
One very i mportant el ement: os.
puts $tcl_platform(os);
# On Solaris:
> SunOS
# On Windows NT or Windows 2000:
> Windows NT
# On Linux:
> Linux
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 51
OS Envi ronment Access
env array
Wi ndows:
puts [array names env];
> HOME PROCESSOR_IDENTIFIER ComSpec HOMEDRIVE ALLUSERSPROFILE
PROCESSOR_REVISION PATHEXT LOGONSERVER USERDOMAIN PROCESSOR_LEVEL
USERPROFILE USERNAME Os2LibPath COMPUTERNAME TMP SystemRoot
PROCESSOR_ARCHITECTURE OS ProgramFiles APPDATA CLASSPATH DirCmd
CommonProgramFiles windir Path TEMP HOMEPATH SystemDrive QTJAVA
NUMBER_OF_PROCESSORS
#
puts $env(windir);
> C:\WinNT
Sol ari s:
puts [array names env];
> VCS_SWIFT_NOTES DTXSERVERLOCATION HOME LANG LOGNAME TAURUS_HOME
PT_HOME VCS_HOME HOST SHELL XMICONSEARCHPATH SNPSLMD_LICENSE_FILE
LC_CTYPE dtstart_sessionlogfile MACHTYPE OSTYPE LC_TIME SESSION_SVR TZ
TEMP USER MANPATH LC_NUMERIC LC_COLLATE VIM HELPPATH OPENWINHOME SHLVL
TMP DTHELPSEARCHPATH PATH DTSCREENSAVERLIST EDITOR DTDATABASESEARCHPATH
PWD TERMINAL_EMULATOR LMC_HOME DISPLAY VENDOR AB_CARDCATALOG ASTRO_HOME
XMBINDDIR JUPIT_HOME WINDOWID LC_MONETARY LC_MESSAGES LM_LICENSE_FILE
MAIL XFILESEARCHPATH DTAPPSEARCHPATH GROUP XMICONBMSEARCHPATH TERM
HOSTTYPE SYNOPSYS DTUSERSESSION DC_HOME
puts $env(TMP)
> /tmp
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 52
Error Handl i ng: The catch Command
Syntax:
catch command_to_be_run ?error_message_variable?
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 53
Error Handl i ng: Safe Fi l e I /O
$errorInfo. Wri tten i nto a vari abl e by the catch command
# Read the first line from a file and print it to the screen:
proc readLine1 { Fname } \
{if { [catch {set Fr [open $Fname r]} ErrMsg]!=0 } \
{puts stderr "readLine1(): Open \[$Fname\] for read failed.\n";
puts stderr "$ErrMsg.";
return -1;
} \
else {gets $Fr Line;
puts "readLine1\($Fname\): \[$Line\].";
close $Fr;
};
}
#
readLine1 /etc/passwd;
> readLine1(): Open [/etc/passwd] for read failed.
>
> couldn't open "/etc/passwd": no such file or directory.
readLine1 C:/WinNT/welcome.ini;
> readLine1(C:/WinNT/welcome.ini): [[Deleted]].
Defaul t message: > couldn't open "/etc/passwd": no such file or directory.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 54
OS-Access Commands I
cd. Change pwd.
pwd. Report pwd.
time. Benchmarki ng uti l i ty.
time {readLine1 C:/WinNT/welcome.ini} 3
> readLine1(C:/WinNT/welcome.ini): [[Deleted]].
> readLine1(C:/WinNT/welcome.ini): [[Deleted]].
> readLine1(C:/WinNT/welcome.ini): [[Deleted]].
> 765.333333333 microseconds per iteration
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 55
OS-Access Commands I I
eval. I nvokes new i nterpreter i nstance; executes a l i st.
interp. Same as eval , but new i nstance i s restri cted.
exec. Cal l s the OS to run an OS command.
set Contents [exec tar tvf ex.tar];
#
puts $Contents;
> drwxr-xr-x user/dos 0 2006-04-12 08:13 Lab01/
> drwxr-xr-x user/dos 0 2006-04-12 08:13 Lab01/Lab01_Ans/
> -rw-r--r-- user/dos 140 2006-06-23 01:32 Lab01/Lab01_Ans/Lab01_Ans07.tcl
> -rw-r--r-- user/dos 597 2006-06-23 01:34 Lab01/Lab01_Ans/Lab01_Ans08.tcl
... (lines omitted) ...
> -rw-r--r-- user/dos 91 2006-06-23 01:30 Lab02/Lab02_Ans/Lab02_Ans06.tcl
#
set env(PATH) .;
set Contents [exec tar tvf ex.tar];
> couldn't execute "tar": no such file or directory
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 56
Advanced Fi l e I /O: read
# Count the words in a file:
proc countWords { Fname } \
{
if { [catch {set Fr [open $Fname r]} ErrMsg]!=0 } \
{
puts stderr "countWords(): Open \[$Fname\] for read failed.\n";
puts stderr "$ErrMsg.";
return -1;
} \
else {
set Count [llength [split [read $Fr]]];
close $Fr;
};
return $Count;
}
set FileName "C:/WinNT/system.ini";
puts "$FileName has [countWords $FileName] words.";
> C:/WinNT/system.ini has 25 words.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 57
Advanced Fi l e I /O: seek & tell
Exampl e. Ex.txt contai ns the output of the array statistics
("buckets") exampl e previ ousl y shown (see Textbook):
set FileName "Ex.txt";
set Fr [open $FileName r];
seek $Fr 100 start;
gets $Fr Seek100;
puts "Seek100=\[$Seek100\] tell=[tell $Fr].";
> Seek100=[ in table, 4 buckets] tell=121.
#
seek $Fr 100 current;
gets $Fr Seek200;
puts "Seek200=\[$Seek200\] tell=[tell $Fr].";
> Seek200=[ries: 0] tell=229.
#
seek $Fr -10 end;
gets $Fr SeekEnd10;
puts "SeekEnd10=\[$SeekEnd10\] tell=[tell $Fr].";
> SeekEnd10=[ntry: 1.0] tell=377.
#
close $Fr;
Note: We i gnore fi l e-rel ated concurrent commands fcopy, fblocking, socket,
update, and vwait.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 58
file: Data Access Commands
We'l l study the fol l owi ng four commands; they al l access the data contai ned
i n a fi l e, rather than the attri butes or status of the fi l e i n the fi l i ng system.
file copy
file mkdir
file rename
file delete
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 59
file: Data Access I
file copy; file rename
# Copy a file or directory:
proc copyStuff { SrcList DstName } \
{
# Weak quotes for catch expands $SrcList:
if { [catch "file copy $SrcList $DstName" ErrMsg]!=0 } \
{puts stderr "copyStuff(): copy \[$SrcList\] $DstName failed.\n";
puts stderr "$ErrMsg.";
return -1;
} \
else { puts "copyStuff -->\[[glob -tails -directory $DstName *]\]."; }
}
#
set SrcList [glob -directory "C:/WinNT" welc*];
set DstName "D:/temp";
set DstBefore [glob -nocomplain -tails -directory $DstName *];
puts "Copying \[$SrcList\] to $DstName. dest listing=\[$DstBefore\].";
> Copying [C:/WinNT/welcome.exe C:/WinNT/welcome.ini] to D:/temp. dest listing=[].
#
copyStuff $SrcList $DstName;
> copyStuff -->[welcome.exe welcome.ini].
#
copyStuff $SrcList $DstName;
> copyStuff(): copy [C:/WinNT/welcome.exe C:/WinNT/welcome.ini] D:/temp failed.
>
> error copying "C:/WinNT/welcome.exe" to "D:/temp/welcome.exe": file already exists.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 60
file: Data Access I I
file mkdir
# Create one or more directories:
proc makeDirs { DirList } \
{
# Weak quotes for catch expands $DirList:
if { [catch "file mkdir $DirList" ErrMsg]!=0 } \
{puts stderr "makeDirs(): file mkdir \[$DirList\] failed.\n";
puts stderr "$ErrMsg.";
return -1;
} \
else { puts "all OK."; }
}
#
set DirList [list NewDir1 NewDir2];
makeDirs $DirList;
> makeDirs(): file mkdir [NewDir1 NewDir2] failed.
>
> can't create directory "NewDir1": file already exists.
file delete. (fi l es or di rectori es)
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 61
file: Context and Name Commands
file system (context)
file volumes (context)
file pathtype
file separator
file split
file nativename
file normalize (context)
file dirname
file rootname
file tail
file extension
file join
file readlink
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 62
file: Fi l e Access Commands
file exists
file type
file size
file owned
file readable
file writable
file executable
file stat
file lstat
file isdirectory
file isfile
file attributes
file atime
file mtime
file channels
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 63
The TcL I nterpreter
Interactive operation:
• Text output by a TcL command wi l l be pri nted automati cal l y to the
screen.
• eof character
Thi s i s control-Z; don't l et the i nterpreter read thi s char from a fi l e
(sourced) or the keyboard i n Wi ndows! Use \x1a (hex) or \032
(octal ) to mani pul ate i t or send i t to stdout.
General l y not an i ssue i n Li nux or Uni x.
• history command
Defaul t i s 20; use history keep to change.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 64
TcL info Command
info globals Li sts gl obal s
info exists Checks vari abl e exi stence
info commands Li sts commands
info functions Mathemati cal functi ons of expr
info hostname
info library
info nameofexecutable
info patchlevel
info tclversion
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 65
Scri pti ng and Debuggi ng
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 66
Scri pt Gui del i nes: General
1. I f the scri pt wi l l be more than a coupl e of l i nes, wri te a comment fi rst,
before wri ti ng any TcL.
2. Begi n every proc wi th a bri ef, descri pti ve comment. Name i t, and i ts
formal arguments, suggesti vel y.
3. Use at l east one upper-case l etter i n every object you decl are.
4. Any coherent col l ecti on of commands shoul d be col l ected i nto a decl ared
proc.
5. Know the bui l ti n features of the l anguage; they can make your work
easi er. For exampl e, why use numeri cal l y-i ndexed parsi ng (string
index; string wordend, ...) when lsearch -inline woul d return
the words sought?
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 67
Scri pt Gui del i nes: Bi g Stuff
1. Desi gn i s words or di agrams, not code. Codi ng general l y i nterferes
wi th desi gn work.
¦ Outl i ne the whol e scri pt i n comments fi rst, before doi ng any TcL.
¦ Wri te out the pl anned processi ng, step-by-step, and ponder, expand,
or correct the comments before any TcL.
¦ Fol l ow the comments wi th empty proc decl arati ons expected to
i mpl ement major parts of the desi gn.
¦ The codi ng shoul d be to fi l l i n the desi gn, not to substi tute for i t.
2. Wri te a bri ef descri pti on of each change or bug fi x, wi th a date and
versi on number, near the start of the scri pt fi l e.
3. For a huge scri pt, consi der namespace decl arati ons (to be descri bed
after next l ab).
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 68
Scri pt Debuggi ng Rul es
Try these, i n order:
Rule 1. Read the fi rst i nterpreter error message careful l y; check at the
l i ne i ndi cated
Rule 2. Check above the l i ne i n the fi rst message.
Rule 3. El i mi nate parenthesi zi ng or mi squoti ng errors:
Use the vi {%} key to jump the cursor to the pai red groupi ng
token.
Turn on vim colorization.
Rule 4. Add your own debuggi ng messages.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 69
Addi ng Debuggi ng Messages
I n addi ti on to your desi gned-i n catch and $errorInfo asserti ons:
• I nsert verbose messages at possi bl e troubl e spots.
• Mai ntai n a l i ne-counter vari abl e when readi ng and parsi ng a fi l e.
Typi cal verbose messagi ng proc:
# Declaration:
proc ErrPrint { Msg {LineNo {(not available)}} } \
{
puts stderr "\nERROR: Line=$LineNo. $Msg.\n";
}
...
# Runtime:
if { $Status!=0 } \
{ ErrPrint "Status=\[$Status\] during ..." $N;
return -1;
}
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 70
Speci al Debuggi ng Commands
¦ trace. Al l ows a user-defi ned proc to be cal l ed automati cal l y whenever
a certai n event occurs.
trace add execution. Cal l ed whenever the speci fi ed command i s
run.
trace add variable. Cal l ed whenever a speci fi ed vari abl e i s
accessed.
¦ unknown. Defi ne thi s proc; i t wi l l be cal l ed whenever a nonexi stent
proc i s i nvoked. The defaul t defi ni ti on i s a proc whi ch si mpl y pri nts,
invalid command name "name_of_undeclared_command".
¦ error. Thi s command generates an error and aborts the i nterpreter.
Mi ght be cal l ed i n a user-defi ned error-message proc.
Syntax:
error output_message $errorI nfo_string $errorCode_string;
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 71
Lab 1 Preface
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 72
Lab 1: Goal s
⇒ Set up an i nformati ve scri pt user i nterface.
⇒ Learn to read and wri te a netl i st fi l e.
⇒ Modi fy the netl i st fi l e data to change al l escaped names to nonescaped
ones.
⇒ Modi fy the netl i st fi l e, usi ng a tabl e i n a si de fi l e, to rename certai n,
sel ected modul e names.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 73
Lab 1: Desi gn Schemati c
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 74
Lab 1: Veri l og "Net-Li st" Exampl e
The schemati c shows an and gate dri vi ng a fl i p-fl op l atchi ng the output
named ParValid, one i nput of whi ch i s the ReadReq i nput and the other of
whi ch i s an i nverted FIFOEmpty.
The netl i st contai ns the fol l owi ng (rearranged):
...
INVD1 U161 ( .I(ReadReq), .ZN(n123) );
NR2D0 U122 ( .A1(n162), .A2(n123), .ZN(N35) );
DFCNQD1 ParValidr_reg ( .D(N35), .CP(ParOutClk), .CDN(n119), .Q(n160) );
CKND0 U162 ( .CLK(n160), .CN(n81) );
DEL4 U109 ( .I(n81), .Z(n74) );
CKNXD16 U110 ( .I(n74), .ZN(ParValid) );
...
The D fl i p-fl op whi ch l atches ParValid i s a DFCNQD1. The and gate i n
the schemati c i s represented by a deMorgani zed nor gate (NR2D0) i n the
netl i st.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 75
Lab 1: Veri l og Netl i st Basi cs
Veri l og netl i st structure. On the l eft, the fi l e i s a sequence of modul e
decl arati ons. On the ri ght, each modul e decl arati on consi sts of a
header, i nput and output port decl arati ons, wi re decl arati ons,
and the col l ecti on of i nstances gi vi ng the modul e i ts functi onal i ty.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 76
Lab 1: Veri l og Exampl e Modul e: Multicounter
module MultiCounter ( CarryOut, Clock, Reset );
input Clock, Reset;
output CarryOut;
wire \Ctr[3] , \Ctr[2] , \Ctr[1] , \Ctr[0] , N1, N2, N3, N4, N5, n1;
MultiCounter_DW01_inc_0
add_16 ( .A({CarryOut, \Ctr[3] , \Ctr[2] , \Ctr[1] ,
\Ctr[0] }), .SUM({N4, N5, N3, N2, N1}) );
DFCNQD1 \Ctr_reg[1] ( .D(N2), .CP(Clock), .CDN(n1), .Q(\Ctr[1] ) );
DFCNQD1 \Ctr_reg[2] ( .D(N3), .CP(Clock), .CDN(n1), .Q(\Ctr[2] ) );
DFCNQD1 \Ctr_reg[3] ( .D(N5), .CP(Clock), .CDN(n1), .Q(\Ctr[3] ) );
DFCNQD1 \Ctr_reg[0] ( .D(N1), .CP(Clock), .CDN(n1), .Q(\Ctr[0] ) );
DFCNQD1 \Ctr_reg[4] ( .D(N4), .CP(Clock), .CDN(n1), .Q(CarryOut) );
I NVD1 U3 ( .I(Reset), .ZN(n1) );
endmodule
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 77
Lab 1: Veri l og I nstanti ati on Syntax
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 78
Lab 1: Netl i st Modi fi cati on
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 79
Mul ti di mensi onal Arrays
TcL hi erarchi cal l i sts make thi s easy:
lset, lappend, lindex correctl y preserve quote hi erarchy.
The stri ng data structure of a
1-el ement, 3-D array:
{ A }
A 2-el ement, 3-D array:
{ { {A B} {C D} }
{ {E F} {G H} } }
A (normal ) 3-el ement, 3-D array:
{ { {A B C} {D E F} {G H I} }
{ {J K L} {M N O} {P Q R} }
{ {S T U} {V W X} {Y Z Ω} }
}
To read out, modi fy, and wri te i n a new val ue
at coordi nates ($i, $j, $k):
set ListLevel2 [lindex $The3DArray $i];
set ListLevel3 [lindex $ListLevel2 $j];
lset ListLevel3 $k ValueToWrite;
lset ListLevel2 $j $ListLevel3;
lset The3DArray $i $ListLevel2;
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 80
TcL exec of OS Commands
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 81
OS Coordi nati on: exec Backgroundi ng
TcL exec does not cal l the shel l di rectl y; does i ts own parsi ng.
vim -g does i ts own backgroundi ng, but thi s causes the scri pt to wai t unti l vi m
termi nates:
proc editFile { Path } \
{
if { [catch {exec vim -g $Path} CatchMsg] } \
{ puts "\neditFile: Start vim to edit \[$Path\].\n $CatchMsg";
return -1;
}
return 0;
}
#
editFile C:/WinNT/welcome.ini
> # vim loads the file in a new graphical window
To background vim -g and l et the scri pt proceed i ndependentl y, add an exec
backgroundi ng word. Change the command to,
exec vim -g $Path &
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 82
OS Coordi nati on: execi ng portabl y
proc execLS { Dir } \
{global tcl_platform;
if { [catch {cd $Dir} Msg] } \
{puts "\nexecLS: can't cd to \[$Dir\]\n$Msg"; return -1;}
switch -glob "$tcl_platform(os)" \
{*[xS]
{if {[catch {set Listing [exec ls -al $Dir]} Msg]} \
{puts "\nexecLS: Attempting \[exec ls -l $Dir\]\n$Msg"; return -1;}
}
default
{set D [file nativename $Dir];
if {[catch {set Listing [exec cmd.exe /c "dir /B $D"]} Msg]} \
{puts "\nexecLS: \
Attempting \[exec cmd.exe /c 'dir /B $D'\]\n$Msg"; return -2;
}
}
}
puts $Listing;
}
# Runtime:
execLS C:/WinNT
> system32 ... (remaining output omitted) ...
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 83
TcL namespace
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 84
Appl i cabi l i ty of namespace
⇒ Not useful for scri pt devel opment.
⇒ Useful for i ndependent devel opment by i ndi vi dual programmers i n a
l arge project.
• Provi des freedom from name confl i ct.
• Permi ts i ntegrati on of separate namespaces bottom-up.
⇒ Di sadvantages wi th respect to C++
• Does not provi de good encapsul ati on.
• Entai l s grave ri sk of fai l ure i f programmers attempt cross-
namespace TcL reci proci ty.
• The requi red error-handl ers greatl y reduce performance.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 85
Decl arati on and Hi erarchy of Namespaces
Use namespace eval for creati on.
namespace eval Space1 \
{ proc Puts { x } { puts "Puts1($x) called."; } }
namespace eval Space2 \
{ proc Puts { x } { puts "Puts2($x) called."; }
namespace eval Space22 \
{ proc Puts { x } { puts "Puts22($x) called."; }
}
#
Space1::Puts "Hello1";
> Puts1(Hello1) called.
#
Space2::Space22::Puts "Hello22";
> Puts22(Hello22) called.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 86
Namespace Rel i abi l i ty
namespace eval Space1 \
{ proc Puts { x } { puts "Puts($x) called."; } }
namespace eval Space1::Space2::Space3 \
{ proc Puts { x } { puts "Puts^3($x) called."; } }
#
Puts "path=::";
> invalid command name "Puts" ... (scri pt aborts)
#
Space1::Puts "path=Space1::";
> Puts(path=Space1::) called.
#
Space3::Puts "path=Space3::";
> invalid command name ... (scri pt aborts)
#
Space1::Space2::Space3::Puts "path=Space1..Space3::";
> Puts^3(path=Space1..Space3::) called.
Never omi t i nvocati on of namespace exists (or, catch) when maki ng any
namespace-dependent reference to a vari abl e or a proc.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 87
Namespace Commands I
namespace delete. Del etes the namespace gi ven and al l namespace eval
constructs associ ated wi th i t. A nonexi stent name causes a fatal error .
namespace exists. Returns a 1 i f the namespace exi sts; otherwi se, 0.
namespace export. The TcL reci proci ty command for fl aggi ng as avai l abl e
a l i st of procs i n the i nvoki ng namespace.
One opti on, -clear.
namespace import. Thi s i s the TcL reci proci ty command whi ch admi ts
access i n the i nvoki ng namespace to procs exported from a di fferent
namespace.
Newl y i mported names are accessi bl e as though they had been decl ared
l ocal l y there.
An attempt to rei mport a name whi ch al ready exi sts i n the i mporti ng
namespace i s a fatal error .
I mporti ng by wi l dcard "*" never causes an error.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 88
namespace import Exampl es
namespace eval S1 \
{ set X "X is OK.";
proc printV { x } { puts $x; };
};
namespace eval S2 { namespace import ::S1::*; };
namespace eval S1 { namespace export printV; };
#
if { [catch {S2::printV $S1::X;}] } {puts "catch: $errorInfo";}
> catch: invalid command name "S2::printV" ... (message shortened)
#
namespace eval S2 { namespace import ::S1::*; };
#
if { [catch {S2::printV $S1::X;}] } {puts "catch: $errorInfo";}
> X is OK.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 89
Namespace Commands I I
namespace forget. Accepts a l i st of names to uni mport.
namespace origin. Accepts a si mpl e command name.
namespace current. Returns the ful l y-qual i fi ed namespace path.
namespace which. Thi s command returns ei ther an empty stri ng, i f not
found, or the ful l y-qual i fi ed namespace path.
Opti ons are -variable and -command (the defaul t).
Di ffers from namespace origin i n that an i mported command wi l l be
descri bed by the path to the i nvoki ng namespace, not to the namespace of
i ts ori gi n.
namespace parent. Accepts a namespace path as an opti onal argument.
namespace children. Returns a compl ete l i st of ful l y-qual i fi ed paths to al l
namespaces di rectl y created i n the i nvoki ng one or i n the (opti onal ) one
named. Onl y one l evel of hi erarchy i s returned.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 90
namespace code Command
¦ namespace code. Assi gns a cal l i ng context to a command. Not useful
i n a scri pt. Maybe use rename (bel ow) i n a scri pt, i nstead.
Exampl e: An S1 command i s stored i n S1 vari abl e P. As shown, the S1
$P then can be eval'ed i n S2 to produce, "S2 is the context.".
namespace eval S1 \
{ set X "S1 is the context.";
proc printV { Xin } { upvar $Xin X; puts $X; };
#set P [namespace code "printV X"];
set P "printV X";
namespace export printV;
};
namespace eval S2 \
{set X "S2 is the context.";
set P $::S1::P
namespace import ::S1::*;
if { [catch {eval $P}] } {puts "catch: $errorInfo";}
};
Del ete set P "printV X" and uncomment the namespace code cal l :
The message becomes "S1 is the context.".
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 91
The variable Command I
A si mpl e exampl e of the use of global i nsi de a namespace:
set X 2;
namespace eval S1 {
proc printX2 {} { global X; puts "X^2=[expr $X*$X]";} }
S1::printX2;
> X^2=4
I f X i s set i n the S1 namespace but not at scri pt l evel , i t i s uni ni ti al i zed:
namespace eval S1 {
set X 3;
proc printX2 {} { global X; puts "X^2=[expr $X*$X]";} }
S1::printX2;
> can't read "X": no such variable ...
We shoul d have cal l ed these procs by catch, ri ght?!
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 92
The variable Command I I
I f we try to fi x thi s by decl ari ng X i n the gl obal namespace agai n, a rather
bi zarre probl em appears:
set X 2;
namespace eval S1 {
set X 3;
proc printX2 {} { global X; puts "X^2=[expr $X*$X]";} }
S1::printX2;
> X^2=9
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 93
The variable Command I I I
The probl em i s resol ved by repl aci ng set wi th variable:
variable X 2; # Thi s makes global work as expected.
namespace eval S1 {
variable X 3;
proc printX2 { } { global X; puts "X^2=[expr $X*$X]";} }
S1::printX2;
> X^2=4
The namespace-l ocal vari abl e X al so can be accessed:
variable X 2;
namespace eval S1 {
variable X 3;
proc printX2 {} {variable X; puts "X^2=[expr $X*$X]";} }
S1::printX2;
> X^2=9
Concl usi on: Avoi d set when namespace stack frames are i nvol ved.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 94
The rename Command
Thi s command can move a proc from one namespace to another.
Exampl e:
variable X 2;
namespace eval S1 {
variable X 3;
proc printX { } { variable X; puts "X=$X"; }
}
S1::printX;
> X=3
rename S1::printX X;
X;
> X=2
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 95
The uplevel Command
Thi s command can cal l a proc i n a context whi ch has been pushed onto the
stack (i s i nto a previ ous cal l er's stack frame).
I nvocati on syntax:
uplevel #n proc proc_args
Thi s i s a ri sky goto-l i ke construct whi ch shoul d be avoi ded i f possi bl e.
Probl em: The uplevel necessari l y wi l l be decl ared i n a proc, and proc
names are by defaul t gl obal . Once a proc has been decl ared, there i s no
good way i n TcL to prevent anythi ng from cal l i ng i t.
Sol uti on: I f access to a cal l er resource i s requi red i n a proc cal l , pass i n
the resource by val ue or by upvar.
Don't confuse upvar and uplevel!
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 96
Namespace Safety Summary
The benefi t of namespace i s that names wi thi n a namespace can not
confl i ct wi th names at scri pt l evel or i n another namespace.
Costs:
• Attempted reuse of procs whi ch i ncl ude set of vari abl es may cause
unexpected errors.
• Codi ng overhead i n error-handl i ng i s consi derabl e.
• Error-handl i ng code wi l l i mpact runti me performance, because every
cal l of catch i nvokes a new i nstance of the TcL i nterpreter.
• Normal TcL reci proci ty among di fferent namespaces i s very ri sky. The
severi ty can be mi ti gated by a wel l -defi ned unknown proc.
Suggestions:
• Pass val ues by vari abl e expressi on or upvar wherever possi bl e.
• Coordi nate di fferent namespace segments of a l arge program by
namespace path references, not by export-i mport reci proci ty.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 97
Lab 2: OS exec; namespace
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 98
TcL Mi scel l aneous Topi cs
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 99
EDA Appl i cati ons
TcL i s used i n control fi l es for:
• synthesi s
• ti mi ng veri fi cati on
• fl oorpl anni ng
• pl ace-and-route
These tool s usual l y wri te journal l i ng fi l es i n TcL.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 100
SDC: An EDA Enhancement of TcL
Synopsys Desi gn Constrai nt l anguage.
• Speci fi cati on i s l i censed freel y (Synopsys Tapin web si te).
• Adds a set of about 60 procs for di gi tal desi gn tool s whi ch use TcL
scri pti ng:
Logi c synthesi s
Netl i st ti mi ng veri fi cati on
Fl oorpl anni ng
Exampl e:
SDC defi nes procs, get_ports() and set_max_delay(); so,
set_max_delay 15 -to [get_ports Z*];
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 101
Packages
package: Col l ecti on of TcL for i ncreased i nterpreter
functi onal i ty.
Mostl y useful for TcL l anguage devel opers, not users.
To use a package, add package require pkg_name to your
scri pt:
package require Tk;
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 102
Enhancements Beyond TcL
• Expect for TcL seri al communi cati on and GUI object
concurrent i nteracti on.
• Tcl X TcL Extended scri pti ng command set : pipe,
kill, fork, fcntl, etc.
• Tk GUI devel opment ki t. Runs i n wish, not tclsh.
• C program hooks: TcL or Tk avai l abl e.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 103
Revi ew and Wrap-Up
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 104
Qui ck Revi ew
Some gui dance on organi zi ng ones work:
• Start codi ng wi th comments;
• put everythi ng reasonabl e i n procs;
• decl are al l procs before runti me.
Know the command detai l s:
• string subcommands
• vari ous list commands
• •• • array subcommands.
Remember your TcL safety net: The catch command.
Be aware of portabi l i ty i ssues. Use info(), $env, and $tcl_platform to
ensure that your scri pt can be run correctl y i n al l requi red OS contexts.
When fi xi ng a bug, remember to read the error message(s) careful l y. I n
extreme cases, add your own temporary debug messages.
2010-05-16 TcL Advanced Scri pt Workshop Sl i de 105
That's I t
(pl ease fi l l out eval uati on)

2010-05-16

TcL Advanced Script Workshop

List of Slides
Course Organization .................................................................................................................................................................................................1 Introduction and Scope .............................................................................................................................................................................................2 Today's Agenda ....................................................................................................................................................................................................3 Topics ....................................................................................................................................................................................................................3 Schedule................................................................................................................................................................................................................3 References and Online Help................................................................................................................................................................................4 What is a "Script"? ...............................................................................................................................................................................................5 Script Languages .................................................................................................................................................................................................6 TcL Language Properties (Review).....................................................................................................................................................................7 Strings........................................................................................................................................................................................................................8 String: A Vector of Characters ...........................................................................................................................................................................9 String Reading Command List..........................................................................................................................................................................10 String Reading Commands I .............................................................................................................................................................................11 string length Example: ......................................................................................................................................................................................12 String Reading Commands II............................................................................................................................................................................13 Regular expression basics..................................................................................................................................................................................14 String Reading Commands III ..........................................................................................................................................................................15 String Reading Commands IV ..........................................................................................................................................................................16 String Reading Commands V............................................................................................................................................................................17 String Reading Commands VI ..........................................................................................................................................................................18 String Reading Commands VII .........................................................................................................................................................................19 Example: Reading a Shopping List..................................................................................................................................................................20 Shopping List Code ............................................................................................................................................................................................21 String Reading Commands VIII .......................................................................................................................................................................22 Quoting Problems ..............................................................................................................................................................................................23 String Writing Command List ..........................................................................................................................................................................24 String Writing Commands I..............................................................................................................................................................................25 String Writing Commands II ............................................................................................................................................................................26 String Writing Commands III ...........................................................................................................................................................................27 String Writing Commands IV ...........................................................................................................................................................................28 String Writing Commands V.............................................................................................................................................................................29 String Writing Commands VI ...........................................................................................................................................................................30 Lists..........................................................................................................................................................................................................................31

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->