TclTk-02 - Interra Systems

coordinatedcapableSoftware and s/w Development

Nov 4, 2013 (3 years and 8 months ago)

109 views

Slide:
1

Training 2000

Tcl programming


Faculty

Surya Pratik Saha

e
-
mail : spsaha@cal.interrasystems.com

Interra Systems India Pvt. Ltd
.

Slide:
2

Training 2000

What I’ll do


Give an overview of the Tcl language


Using Tk commands from Tcl script


C interface of Tcl

Slide:
3

Training 2000


Overview of Tcl/Tk


Component technologies:


Tcl: embeddable scripting language


Tk: GUI toolkit and widgets based on Tcl


The principle:


universal scripting language controls everything: functions,
interfaces, communication.


Results:


Raise the level of GUI programming: simpler, 5
-
10x faster
development time than X, raw Win32


programmable applications work together; cross
-
platform
delivery


Active objects: replace data with scripts

Slide:
4

Training 2000

Overview of Tcl/Tk


Interactive programs need command languages:


Typically redone for each application.


Result: weak.


Solution: reusable scripting language.


Interpreter is a C library.


Provides basic features: variables, procedures, etc.


Applications extend with additional features
.


Slide:
5

Training 2000

Tcl: Tool Command Language


Simple syntax (similar to sh, C, Lisp):


set a 50






Substitutions:


set b $a






獥琠戠孥硰爠②⬱そs






Quoting:


set b "a is $a"



愠楳‵a


獥琠戠筛數灲․愫㄰嵽s


孥硰爠②⬱そ

Slide:
6

Training 2000

More On The Tcl Language


Rich set of built
-
in commands:


Variables, associative arrays, lists


C
-
like expressions


Conditionals, looping
:


if "$x < 3" {

puts "x is too small"

}


Procedures


Access to files, subprocesses, network sockets

Slide:
7

Training 2000

More On The Tcl Language


Only data representation is zero
-
terminated strings:


Easy access from C.


Programs and data interchangeable.


set cmd1 "exec notepad"

...

eval $cmd1

(
notepad.exe launches under Windows
)




Unfortunately, no 8
-
bit data


Slide:
8

Training 2000

Defining Procedure


Defining and using procedures is easy


proc fac x {

if $x<=1 {return 1}

expr $x*[fac [expr $x
-
1]]

}


fac 4








Slide:
9

Training 2000


Tcl Language Programming

There are two parts to learning Tcl:

1. Syntax and substitution rules:


Substitutions simple, but may be confusing at first.

2. Built
-
in commands:


Can learn individually as needed.


Control structures are commands, not language syntax
.

TCL HAS NO FIXED GRAMMAR

Slide:
10

Training 2000

Basics


Tcl script


Sequence of commands.


Commands separated by newlines, semi
-
colons
.


Tcl command


One or more words separated by white space.


First word is command name, others are arguments.


Returns string result
.


Examples:

set a 22
set the variable ‘a’ to
22

puts "Hello, World!"
world’s shortest
program

Slide:
11

Training 2000

Division Of Responsibility

Tcl Parser

Command Procedure

Command

Words

Result

Interprets words.

Can invoke parser recursively.

Produces string result.

Chops commands into words.

Makes substitutions.

Does not interpret values of words.

Single pass operation!

Slide:
12

Training 2000

Controlling Word Structure

Words break at white space and semi
-
colons, except:

Double
-
quotes prevent breaks
:

set a "x is $x; y is $y"

Curly braces prevent breaks and substitutions
:

set a {[expr $b*$c]}

Backslashes quote special characters
:

set a word
\

with
\

\
$
\

and
\

space

Backslashes can escape newline (continuation)

Substitutions don't change word structure:

set a "two words"

set b $a

Slide:
13

Training 2000

Variable Substitution

Syntax:
$
varName

Variable name is letters, digits, underscores.

May occur anywhere in a word.

It is not necessary to declare before use.

Sample command

Result

set b 66

66

set a b

b

set a $b

66

set a $b+$b+$b

66+66+66

set a $b.3

66.3

set a $b4

no such variable

Slide:
14

Training 2000

Command Substitution

Syntax: [
script
]

Evaluate script, substitute result.

May occur anywhere within a word.

Sample command

Result

set b 8

8

set a [expr $b+2]

10

set a "b
-
3 is [expr $b
-
3]"

b
-
3 is 5

Slide:
15

Training 2000

Summary of Tcl Command Syntax

Command: words separated by whitespace

First word is a function, others are arguments

Only functions apply meanings to arguments

Single
-
pass tokenizing and substitution

$ causes variable interpolation

[ ] causes command interpolation

“” prevents word breaks

{ } prevents all interpolation

\

escapes special characters

TCL HAS NO GRAMMAR!

Slide:
16

Training 2000

Tcl Math Expressions


C
-
like (int and double)


Command, variable substitution occurs
within

expressions.


Used in
expr

command
.

Sample command


Result

set b 5



5

expr ($b*4)
-

3

17

expr $b <= 2


0

expr $a * cos(2*$b)

-
5.03443

expr {$b * [fac 4]}

120



Tcl promotes integers to reals when needed


All values translated to the same type


Note that
expr

knows about types, not Tcl

Slide:
17

Training 2000

Tcl Math Expressions


What’s happening in these expressions
?


expr $a * cos(2*$b)




-
5.03443


$a, $b substituted by scanner before expr is called


expr {$b * [fac 4]}




120


here, $b is substituted by expr itself


Therefore, expressions get substituted more than once




set b
\
$a



set a 4



expr $b * 2





8

Slide:
18

Training 2000

Tcl Lists


Zero or more elements separated by white space:

red green blue


Braces and backslashes for grouping:

a b {c d e} f (4 words)

one
\

word two three (3 words)


List
-
related commands:

concat

lindex

llength

lsearch

join

linsert

lrange

lsort

lappend

list


lreplace split


Note: all indices start with 0.
end

means last element


Examples:

lindex {a b {c d e} f} 2



挠搠e

汳l牴⁻ 敤 杲g敮⁢ 略}



扬略b杲敥渠牥r

Slide:
19

Training 2000

Tcl Lists ( Contd... )


list command



Constructs a list



Adds automatic quoting


Example

set x {1 2}


ㄠ1

獥琠礠景s

††


景f

set l1 [list $x “a b” $y]


笱{㉽⁻愠扽⁦潯


set l2 “
\
{$x
\
} {a b} $y”


{1 2} {a b} foo

Slide:
20

Training 2000

Tcl Lists ( Contd... )


lappend command


Appends elements to the end of the list


Adds automatic braces to group argument values


Example


set l1 {1 2}


ㄠ2


lappend l1 3 “4 5”



ㄠ㈠㌠笴‵{


concat command


Concats lists to a top level list


Elements of each list becomes elements of top level list


Example


set l1 {1 2}


ㄠ2


concat $l1 3 “4 5”




ㄠ㈠㌠㐠4

Slide:
21

Training 2000

Tcl Lists ( Contd... )


linsert command


Inserts elements before the element at specified position


Returns a new list


Example


set l1 {1 2}


ㄠ2


linsert $l1 0 “4 5”


{4 5} 1 2


lreplace command


Replaces a range of list elements with new elements


Returns a new list


Example


set l1 {1 2 {3 4} 5}


ㄠ㈠笳2㑽45


lreplace $l1 1 2 “4 5”



ㄠ笴‵素5

Slide:
22

Training 2000

Tcl Lists ( Contd... )


split command


Turns a string into a list


Default separator is white space


Example


set l1 {lp:Line Printer :/usr/spool/lp}

汰l䱩湥n偲i湴n爠㨯:獲/獰s潬⽬/


獰s楴․ ㄠ:



lp {Line Printer } /usr/spool/lp


join command


Converts a list to string


Example


join {1 {2 {3 4}} {5 6}} :




ㄺ㈠笳{㑽㨵46

Slide:
23

Training 2000

Tcl Arrays


Tcl arrays are 'associative arrays': index is any string

set x(fred) 44

set x(2) [expr $x(fred) + 6]


The value of an array element is obtained with $
substitution.

Set foo $x(fred)



44


Never use same variable as both an array and a normal
variable

set arr(0) 1

set arr 3



can’t set “arr”: variable is array

Slide:
24

Training 2000

Tcl Arrays ( Contd…)


Array
-
related commands

anymore get set

exists names size

donesearch nextelement startsearch


names command


Returns the list of indices defined in array

foreach index [ array names
arr pattern
] {

#use arr($index)

}


get command


Returns a list that alternates between index and
corresponding array value

Slide:
25

Training 2000


String manipulation commands:

regexp

format

string

regsub

scan

append


string

subcommands





Note: all indexes start with 0.
end

means last
char

String Manipulation

compare
first
last
index
length
match
range
toupper
tolower
trim
trimleft
trimright
wordend
wordstart
Slide:
26

Training 2000

Globbing & Regular Expressions


"Globbing"
-

a simple pattern language


* means any sequence of characters


? matches any one character


[
chars
] matches a set of characters


Good for filename matching


*.exe

,
[A
-
E]*.txt


glob

command applies a glob pattern to filenames


foreach f [glob *.exe] {

puts "$f is a program"


}

Slide:
27

Training 2000

Globbing & Regular Expressions


"Regular Expressions" are a powerful pattern language


.

(period) matches any character


^

matches start of a string


$

matches end of a string


\
x

single character escape


[
chars
]

matches any of
chars.

^: not.
-
: range.


(
regexp
)
matches the regexp


* matches 0 or more of the preceding


+ matches 1 or more of the preceding


? matches 0 or 1 or the preceding


| can be used to divide alternatives.

Slide:
28

Training 2000

Globbing & Regular Expressions


Examples:


[A
-
Za
-
z0
-
9_]+
: valid Tcl identifiers


T(cl|k)
: Tcl or Tk


regexp

command


regexp T(cl|k) "I mention Tk" w t





牥瑵牮猠s
 慴捨⤬⁷⁢散e浥猠≔欢Ⱐ琠来瑳k≫"


regsub command


regsub
-
nocase perl "I love Perl" Tcl mantra





牥瑵牮猠s
 慴捨⤬慮瑲) 来瑳g≉ 汯癥⁔捬c


regsub
-
nocase {Where's ([a
-
z]*)
\
?}
\


"Where's Bob?"{Who's
\
1?} result





牥瑵牮猠s
 慴捨⤬⁲敳畬琠来瑳)≗桯❳⁂'房"

Slide:
29

Training 2000

The format and scan Commands


format does string formatting.

format "I know %d Tcl commands" 97



í

I know 97 Tcl commands


has most of printf's capabilities


can also be use to create complex command strings


scan is like scanf


set x "SSN#: #148766207"


scan $x "SSN#: %d" ssn


puts "The social security number is $ssn"



í

The social security number is 148766207

Slide:
30

Training 2000

Control Structures


C
-
like in appearance.


Just commands that take Tcl scripts as arguments.


Example: list reversal. Set list b to reverse of list a:


set b ""

set i [expr [llength $a]
-

1]

while {$i >= 0} {


lappend b [lindex $a $i]


incr i
-
1

}


Commands:


if

for

switch

break


foreach

while

eval


continue


source return error

Slide:
31

Training 2000

Control Structure Examples


if

boolean
-
expr ?then? Body1 ?elseif? ?body2? ?else?
?body3?


for

initial test final body

for {set i 0} {$i<10} {incr i} {…}


switch

?flag? value {p1 s1 p2 s2...}


foreach
loopvar valuelist body

foreach name $my_name_list {

switch
-
regexp $name {

^Pete* {incr pete_count}

^Bob|^Robert {incr bob_count}

default {incr other_count}


}

}

Slide:
32

Training 2000

More on Control Structures


Watch out brackets in control structures


set x 3


if $x>2 {... <=
this is OK, eval’ed once


while $x>2 {... <=
this is NOT OK, possible


infinite loop


while {$x>2} {...


<=
this is OK


set a {red blue green}


foreach i $a <=

this is OK


foreach I red blue green {...



<=

NOT OK!

Slide:
33

Training 2000

Procedures


proc

command defines a procedure:

proc sub1 x {expr $x
-
1}


Procedures behave just like built
-
in commands:

sub1 3




2


Arguments can have default values:

proc decr {x {y 1}} {


expr $x
-
$y

}

name

list of argument
names

body

Slide:
34

Training 2000

Procedures and Scope


Scoping: local and global variables.


Interpreter knows variables by their name and scope


Each procedure introduces a new scope


global
procedure makes a global variable local

set x 10

proc deltax {d} {

set x [expr $x
-
$d]

}

deltax 1


can't read x: no such variable

proc deltax {d} {

global x

set x [expr $x
-
$d]

}

deltax 1


9

Slide:
35

Training 2000

Procedures and Scope ( Contd…)


Note that
global

is an ordinary command


proc tricky {varname} {

global $varname

set $varname "passing by reference”

}


upvar

and
uplevel

let you do more complex things


level naming:


#
num
: #0 is global, #1 is one call deep, #2 is 2…


num
: 0 is current, 1 is caller, 2 is caller's caller…

proc incr {varname} {

upvar 1 $varname var

set var [expr $var+1]

}


Slide:
36

Training 2000

Procedures and Scope ( Contd…)

upvar

is used to pass the name of a variable to
procedure


upvar ?level? varname localvar

Default value of level is 1

Mainly used to modify array of outer scope
within a procedure.

Set x(1) delsoft


set x(2) calcutta

proc p {} {

upvar #0 x l

puts [array names l]

set l(1) kausik

}


p



1 2


kausik

Set x(1) delsoft


set x(2) calcutta

proc p {a} {

upvar $a l

puts [array names l]

set l(1) kausik

}


p x



1 2


kausik

Slide:
37

Training 2000

Procedures and Scope ( Contd…)


uplevel

does for code what
upvar

does for variables

proc loop {from to script} {

set i $from

while {$i <= $to} {

uplevel $script

incr i

}

}

set s ""

loop 1 5 {set s $s*}

puts $s





⨪⨪⨠

Slide:
38

Training 2000

Procedures and Scope ( Contd…)


Variable
-
length argument lists:

proc sum args {

set s 0

foreach i $args {

incr s $I

}

return $s

}


sum 1 2 3 4



10

sum



0

Slide:
39

Training 2000

Errors


Errors normally abort commands in progress, application
displays error message:

set n 0

foreach i {1 2 3 4 5} {

set n [expr {$n + i*i}]

}



syntax error in expression "$n + i*i"


Global variable
errorInfo

provides stack trace:

set errorInfo



syntax error in expression "$n + i*i"


while executing

"expr {$n + i*i}"


invoked from within

"set n [expr {$n + i*i}]..."


("foreach" body line 2)


...

Slide:
40

Training 2000

Advanced Error Handling


Global variable
errorCode

holds machine
-
readable
information about errors (e.g. UNIX
errno

value).


NONE
(in this case)


Can intercept errors (like exception handling):

catch {expr {2 +}} msg



ㄠ†
(catch returns 0=OK, 1=err, 2= return, 3=break,


4=continue, other user defined
values...)

set msg



獹s瑡t 敲e潲o楮⁥硰牥獳so渠∲"⬢


You can generate errors yourself

error "bad argument"

return
-
code error "bad argument"

Slide:
41

Training 2000

Tcl File Handling


Tcl file I/O commands:

open

gets

seek

flush


glob

close

read

tell

cd




puts

source

eof

pwd

filename


File commands use 'tokens' to refer to files

set f [open "myfile.txt" "r"]



晩汥f

灵瑳p⑦•$r楴攠i桩猠he硴⁩x瑯⁦tl攢

捬潳c․

Slide:
42

Training 2000

Tcl File Handling ( Contd…)


gets and puts are line oriented

set x [gets $f]
reads one line of $f into x


read

can read specific numbers of bytes

read $f 100



⡵瀠瑯‱〰⁢祴敳映晩汥․昩


seek
,
tell
, and
read

can do random
-
access I/O

set f [open "database" "r"]

seek $f 1024

read $f 100



(bytes 1024
-
1123 of file $f)

Slide:
43

Training 2000

Tcl File Handling ( Contd…)


join

file join d a/b c



搯愯戯d

晩汥f橯楮jd 愯 ⁣



⽡⽢⽣


dirname

file dirname a/b/c/d



愯戯a


tail

file tail a/b/c/d



d

Slide:
44

Training 2000

Two useful Tcl Commands


exec
starts processes, and can use '&'

set FAVORITE_EDITOR emacs

exec $FAVORITE_EDITOR &


eval
reinterprets string as command

set string “Hello, World”

set cmd {puts $string}

… …

eval $cmd



䡥汬漬⁗潲汤

Slide:
45

Training 2000

Runtime Information Facilities


Command line arguments


argc is count, argv0 is interp name, argv is list of args


Tcl/Tk version


tcl_version, tk_version (8.0, 8.0)


Platform
-
specific information


tcl_platform array


byteOrder, osVersion, machine, platform, os


bigEndian, 5.5.1, sun4m, unix, SunOS

Slide:
46

Training 2000

Runtime Information Facilities(Contd…)


The
info

command

what variables are there?


info vars, info globals, info locals, info
exists

what procedures have I defined, and how?


info procs, info args, info default, info
body, info commands


the
rename

command


can rename any command, even built
-
in


can therefor replace any built
-
in command

Slide:
47

Training 2000

Wish: Windowing Shell


Create user interfaces by writing Tcl scripts.


Hello, world:

button .hello
-
text "Hello, world"
-
command exit

pack .hello


Simple directory browser: 30 lines


Web browser: 2000 lines


10x less code for simple things.

Slide:
48

Training 2000

Extending Tcl: Outline


Philosophy: focus on primitives.


Basics: interpreters, executing scripts.


Implementing new commands.


Managing packages; dynamic loading.


Managing the result string.


Useful library procedures: parsing, variables, lists, hash
tables.

Slide:
49

Training 2000

Philosophy


Usually better to write Tcl scripts than C code:


Faster development (higher level, no compilation).


More flexible.


Why write C?


Need access to low
-
level facilities (hardware).


Efficiency concerns (iterative calculations).


Need more structure (code is complex).


Implement new Tcl commands :


Low
-
level to provide independent access to all key features.


High
-
level to hide unimportant details, allow efficient
implementation
.

Slide:
50

Training 2000

Embedding Tcl In Applications


Application generates scripts.


Tcl parses scripts, passes
words to command
procedures.


Application extends built
-
in
command set:


Define new object types in C.


Implement primitive operations
as new Tcl commands.


Build complex features with Tcl
scripts.

Parser

Init

Command

Loop

Application
Commands

Built
-
In
Commands

Tcl

Application


Note that the command loop can also be in the Tcl/Tk box.

Slide:
51

Training 2000

Extensions


Extensions can be developed independently:


Network communication, database access, security, ...


Applications can include combinations of extensions.

Parser

Init

Command

Loop

Application
Commands

Built
-
In
Commands

Tcl

Application

Extension
Commands

Extension