SlideShare a Scribd company logo
1 of 27
Programming Using Tcl/Tk




These slides are based upon
  several Tcl/Tk text books
  material byDr. Ernest J. Friedman-Hill
What you’ll need
PCs in the Computer Science Lab have it installed
 – Start / Tcl / Wish
– Start / Widget tour
Or install it on your own computer
– Windows & Macintosh: free binaries available
– Most Unix: source available
Documentation
    • books can be bought (bookstore, etc)
    • books in the PC lab
– up-to-date man pages on-line
    • Start / Help
What is Tcl/Tk?
Tcl
 – a scripting language
– can be extended in C (but this is harder)
– ugly but simple
Tk
 – a simple but powerful widget set
– Hello World: a complete program that exits when a
  person presses the button


    • grid [ button .myButton -text "Hello World" -command exit ]
Simple things are simple, hard things are possible
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.
Scripts and Commands
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   myName Saul
puts "My Name is $myName”
set class CPSC-481; puts -nonewline $class
Arguments
Parser assigns no meaning to arguments (quoting by
default, evaluation is special):
set x 4              x is "4 "
set y x+10           y is "x+10”
set z $x+10          z is "4+10”


Different commands assign different meanings to their
arguments. “Type-checking” must be done by commands
themselves.
expr 24/3              arg is math expresson -> 8
eval "set a 122"       evaluate argument as a command
button .b -text Hello -fg red some args are options (the -)
string length Abracadabra        some args are qualifiers (length)
Variable Substitution
Syntax: $varName
Variable name is letters, digits, underscores.
 – This is a little white lie, actually.
May occur anywhere in a word.
     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
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
Controlling Word Structure
Words break at white space and semi-colons, except:
– Double-quotes prevent breaks:
   set a 4; set y 5
   set a "x is $x; y is $y"
   -> x is 4; y is 5
– Curly braces prevent breaks and substitutions:
   set a {[expr $b*$c]}
   ->[expr $b*$c]
– Backslashes quote special characters:
   set a word with $ and space
   ->word with $ and space
Controlling Word Structure
            (continued)
– Backslashes can escape newline (continuation)
   • set aLongVariableNameIsUnusual 
     “This is a string”
     -> This is a string


– Substitutions don't change word structure:
   • set a "two words"
     set b $a
     -> two words
Comments
The # is the comment command
Tcl parsing rules apply to comments as well
 set a 22; set b 33                   <- OK
 # this is a comment                  <- OK
 set a 22 # same thing?               <- Wrong!
 set a 22 ;# same thing               <- OK
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!
Tcl Expressions
Arguments are interpretted as expressions in some
commands: expr, if, ...
    Sample command                Result
    set b 5                       5
    expr ($b*4) - 3               17
    expr $b <= 2                  0
    expr {$b * cos(4)}            -3.268…
Some Tcl operators work on strings too
(but safer to use the string compare command)
    set a Bill                    Bill
    expr {$a < "Anne"}            0
    expr {$a < "Fred"}            1
Tcl Arrays
Tcl arrays are 'associative arrays': index is any string
– set foo(fred) 44                          ;# 44
– set foo(2) [expr $foo(fred) + 6]          ;# 50
– array names foo                           ;# fred 2

You can 'fake' 2-D arrays:
set A(1,1) 10
set A(1,2) 11
array names A
=>   1,1 1,2       (commas included in names!)
Lists
Zero or more elements separated by white space:
 set colors {red green blue}
Braces and backslashes for grouping:
 set hierarchy {a b {c d e} f})
 set two_item_list {one two two}
List-related commands:
 concat         lindex       llength        lsearch
 foreach        linsert      lrange         lsort
 lappend        list         lreplace
Note: all indices start with 0. end means last element
Examples:
lindex {a b {c d e} f} 2             c d e
lsort {red green blue}               blue green red
String Manipulation
String manipulation commands:
regexp format            split         string
regsub scan join
string subcommands
compare first         last     index     length
match     range     toupper      tolower       trim
trimleft       trimright
Note: all indexes start with 0. end means last char
    • string tolower "THIS"             ;# this
    • string trimleft “XXXXHello”       ;# Hello
    • string index “abcde” 2            ;# c
Control Structures
C-like in appearance.
Just commands that take Tcl scripts as arguments.
Commands:
  if            for       switch      break
  foreach       while     eval        continue
if else

set x 2
if {$x < 3} {
    puts "x is less than 3"
} else {
    puts "x is 3 or more"
}
while
#list   reversal
set a   {a b c d e}
set b   "”
set i   [expr [llength $a] - 1]
while   {$i >= 0} {
        lappend b [lindex $a $i]
        incr i -1
}
puts $b
for and foreach
for {set i 0} {$i<10} {incr i} {
    puts $I
}


foreach color {red green blue} {
    puts “I like $color”
}

set A(1) a; set A(2) b; set A(26) z
foreach index [array names A] {
    puts $A($index)
}
switch
set pete_count   0
set bob_count    0
set other_count 0
foreach name {Peter Peteee Bobus Me Bobor Bob} {
      switch -regexp $name {
           ^Pete* {incr pete_count}
           ^Bob|^Robert {incr bob_count}
           default {incr other_count}
      }
  }
puts "$pete_count $bob_count $other_count"
Procedures
 proc command defines a procedure:
  proc decrement {x} {
name
      expr $x-1               body
  }   list of argument names

Procedures behave just like built-in commands:
 decrement 3        2
Arguments can have default values:
 proc decrement {x {y 1}} {
     expr $x-$y
 }
 decrement 100 5        ;# 95
 decrement 100          ;# 99
Procedures
Procedures can have a variable number of arguments
 proc sum args {
        set s 0
      foreach i $args {
             incr s $i
        }
        return $s
   }

sum 1 2 3 4 5
  15
sum
  0
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 outside "I'm outside"
set inside     "I'm really outside"
proc whereAmI {inside} {
     global outside
     puts $outside
     puts $inside
}
whereAmI "I wonder where I will be"
-> I'm outside
   I wonder where I will be
Tcl File I/O
Tcl file I/O commands:
open   gets           seek    flush      glob
close  read           tell    cd
fconfigure            fblocked      fileevent
puts   source         eof     pwd filename
File commands use 'tokens' to refer to files
set f [open "myfile.txt" "r"]
=> file4
puts $f "Write this text into file"
close $f
Tcl File I/O
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
=> (up to 100 bytes of file $f)
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)
Tcl Network I/O
socket creates a network connection
set f [socket www.sun.com 80]
fconfigure $f -buffering line
puts $f "GET /"
puts [read $f 100]
close $f
=> The 1st 100 characters from Sun's home page
Network looks just like a file!
To create a server socket, just use
socket -server accept portno

More Related Content

What's hot (20)

Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014Puppet Language 4.0 - PuppetConf 2014
Puppet Language 4.0 - PuppetConf 2014
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Awk programming
Awk programming Awk programming
Awk programming
 
Syntax
SyntaxSyntax
Syntax
 
01c shell
01c shell01c shell
01c shell
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
First steps in C-Shell
First steps in C-ShellFirst steps in C-Shell
First steps in C-Shell
 
Five
FiveFive
Five
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Perl
PerlPerl
Perl
 
1 functions
1 functions1 functions
1 functions
 

Viewers also liked

Tcl2012 8.6 Changes
Tcl2012 8.6 ChangesTcl2012 8.6 Changes
Tcl2012 8.6 Changeshobbs
 
TAO Fayan_Canvas design by tcltk_Final report
TAO Fayan_Canvas design by tcltk_Final reportTAO Fayan_Canvas design by tcltk_Final report
TAO Fayan_Canvas design by tcltk_Final reportFayan TAO
 
The ActiveState of Tcl
The ActiveState of TclThe ActiveState of Tcl
The ActiveState of TclActiveState
 
Tcl tk
Tcl tkTcl tk
Tcl tkTiago
 
Criteria for selecting a research problem
Criteria for selecting a research problemCriteria for selecting a research problem
Criteria for selecting a research problemSelvi Raveendran
 

Viewers also liked (6)

Tcl2012 8.6 Changes
Tcl2012 8.6 ChangesTcl2012 8.6 Changes
Tcl2012 8.6 Changes
 
TAO Fayan_Canvas design by tcltk_Final report
TAO Fayan_Canvas design by tcltk_Final reportTAO Fayan_Canvas design by tcltk_Final report
TAO Fayan_Canvas design by tcltk_Final report
 
Tcl tk howto
Tcl tk howtoTcl tk howto
Tcl tk howto
 
The ActiveState of Tcl
The ActiveState of TclThe ActiveState of Tcl
The ActiveState of Tcl
 
Tcl tk
Tcl tkTcl tk
Tcl tk
 
Criteria for selecting a research problem
Criteria for selecting a research problemCriteria for selecting a research problem
Criteria for selecting a research problem
 

Similar to Unit vii wp ppt

Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell ScriptingRaghu nath
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptxNiladriDey18
 
AARAV NAYAN OPERATING SYSTEM LABORATORY PCA
AARAV NAYAN OPERATING SYSTEM LABORATORY PCAAARAV NAYAN OPERATING SYSTEM LABORATORY PCA
AARAV NAYAN OPERATING SYSTEM LABORATORY PCAAaravNayan
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaewout2
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell ScriptDr.Ravi
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1Dr.Ravi
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-linersdaoswald
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record.toster
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxCatherineVania1
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 

Similar to Unit vii wp ppt (20)

rudra.pptx
rudra.pptxrudra.pptx
rudra.pptx
 
Bash Shell Scripting
Bash Shell ScriptingBash Shell Scripting
Bash Shell Scripting
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
shellScriptAlt.pptx
shellScriptAlt.pptxshellScriptAlt.pptx
shellScriptAlt.pptx
 
Scripting ppt
Scripting pptScripting ppt
Scripting ppt
 
AARAV NAYAN OPERATING SYSTEM LABORATORY PCA
AARAV NAYAN OPERATING SYSTEM LABORATORY PCAAARAV NAYAN OPERATING SYSTEM LABORATORY PCA
AARAV NAYAN OPERATING SYSTEM LABORATORY PCA
 
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaaShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
ShellAdvanced aaäaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Shell programming
Shell programmingShell programming
Shell programming
 
Unix lab manual
Unix lab manualUnix lab manual
Unix lab manual
 
Unix
UnixUnix
Unix
 
Talk Unix Shell Script
Talk Unix Shell ScriptTalk Unix Shell Script
Talk Unix Shell Script
 
Talk Unix Shell Script 1
Talk Unix Shell Script 1Talk Unix Shell Script 1
Talk Unix Shell Script 1
 
Scripting ppt
Scripting pptScripting ppt
Scripting ppt
 
Perl one-liners
Perl one-linersPerl one-liners
Perl one-liners
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 

More from Bhavsingh Maloth

web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh MalothBhavsingh Maloth
 
web programming Unit VIII complete about python by Bhavsingh Maloth
web programming Unit VIII complete about python  by Bhavsingh Malothweb programming Unit VIII complete about python  by Bhavsingh Maloth
web programming Unit VIII complete about python by Bhavsingh MalothBhavsingh Maloth
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHWeb programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHBhavsingh Maloth
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHBhavsingh Maloth
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothBhavsingh Maloth
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothBhavsingh Maloth
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Bhavsingh Maloth
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Bhavsingh Maloth
 
98286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-201298286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-2012Bhavsingh Maloth
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notesBhavsingh Maloth
 

More from Bhavsingh Maloth (20)

web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh Maloth
 
web programming Unit VIII complete about python by Bhavsingh Maloth
web programming Unit VIII complete about python  by Bhavsingh Malothweb programming Unit VIII complete about python  by Bhavsingh Maloth
web programming Unit VIII complete about python by Bhavsingh Maloth
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTHWeb programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
Web programming unit IIII XML &DOM NOTES BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT IV NOTES BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VI BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT V BY BHAVSINGH MALOTH
 
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
 
Web programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh MalothWeb programming UNIT II by Bhavsingh Maloth
Web programming UNIT II by Bhavsingh Maloth
 
Xml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh malothXml dom & sax by bhavsingh maloth
Xml dom & sax by bhavsingh maloth
 
Polytechnic jan 6 2012
Polytechnic jan 6 2012Polytechnic jan 6 2012
Polytechnic jan 6 2012
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007
 
Appsc poly key 2013
Appsc poly key 2013Appsc poly key 2013
Appsc poly key 2013
 
Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007Appscpolytechniclecturersg.s.paper2007
Appscpolytechniclecturersg.s.paper2007
 
Appsc poly key 2013
Appsc poly key 2013Appsc poly key 2013
Appsc poly key 2013
 
98286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-201298286173 government-polytechnic-lecturer-exam-paper-2012
98286173 government-polytechnic-lecturer-exam-paper-2012
 
Unit VI
Unit VI Unit VI
Unit VI
 
Wp unit III
Wp unit IIIWp unit III
Wp unit III
 
Web Programming UNIT VIII notes
Web Programming UNIT VIII notesWeb Programming UNIT VIII notes
Web Programming UNIT VIII notes
 

Unit vii wp ppt

  • 1. Programming Using Tcl/Tk These slides are based upon several Tcl/Tk text books material byDr. Ernest J. Friedman-Hill
  • 2. What you’ll need PCs in the Computer Science Lab have it installed – Start / Tcl / Wish – Start / Widget tour Or install it on your own computer – Windows & Macintosh: free binaries available – Most Unix: source available Documentation • books can be bought (bookstore, etc) • books in the PC lab – up-to-date man pages on-line • Start / Help
  • 3. What is Tcl/Tk? Tcl – a scripting language – can be extended in C (but this is harder) – ugly but simple Tk – a simple but powerful widget set – Hello World: a complete program that exits when a person presses the button • grid [ button .myButton -text "Hello World" -command exit ] Simple things are simple, hard things are possible
  • 4. 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.
  • 5. Scripts and Commands 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 myName Saul puts "My Name is $myName” set class CPSC-481; puts -nonewline $class
  • 6. Arguments Parser assigns no meaning to arguments (quoting by default, evaluation is special): set x 4 x is "4 " set y x+10 y is "x+10” set z $x+10 z is "4+10” Different commands assign different meanings to their arguments. “Type-checking” must be done by commands themselves. expr 24/3 arg is math expresson -> 8 eval "set a 122" evaluate argument as a command button .b -text Hello -fg red some args are options (the -) string length Abracadabra some args are qualifiers (length)
  • 7. Variable Substitution Syntax: $varName Variable name is letters, digits, underscores. – This is a little white lie, actually. May occur anywhere in a word. 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
  • 8. 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
  • 9. Controlling Word Structure Words break at white space and semi-colons, except: – Double-quotes prevent breaks: set a 4; set y 5 set a "x is $x; y is $y" -> x is 4; y is 5 – Curly braces prevent breaks and substitutions: set a {[expr $b*$c]} ->[expr $b*$c] – Backslashes quote special characters: set a word with $ and space ->word with $ and space
  • 10. Controlling Word Structure (continued) – Backslashes can escape newline (continuation) • set aLongVariableNameIsUnusual “This is a string” -> This is a string – Substitutions don't change word structure: • set a "two words" set b $a -> two words
  • 11. Comments The # is the comment command Tcl parsing rules apply to comments as well set a 22; set b 33 <- OK # this is a comment <- OK set a 22 # same thing? <- Wrong! set a 22 ;# same thing <- OK
  • 12. 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!
  • 13. Tcl Expressions Arguments are interpretted as expressions in some commands: expr, if, ... Sample command Result set b 5 5 expr ($b*4) - 3 17 expr $b <= 2 0 expr {$b * cos(4)} -3.268… Some Tcl operators work on strings too (but safer to use the string compare command) set a Bill Bill expr {$a < "Anne"} 0 expr {$a < "Fred"} 1
  • 14. Tcl Arrays Tcl arrays are 'associative arrays': index is any string – set foo(fred) 44 ;# 44 – set foo(2) [expr $foo(fred) + 6] ;# 50 – array names foo ;# fred 2 You can 'fake' 2-D arrays: set A(1,1) 10 set A(1,2) 11 array names A => 1,1 1,2 (commas included in names!)
  • 15. Lists Zero or more elements separated by white space: set colors {red green blue} Braces and backslashes for grouping: set hierarchy {a b {c d e} f}) set two_item_list {one two two} List-related commands: concat lindex llength lsearch foreach linsert lrange lsort lappend list lreplace Note: all indices start with 0. end means last element Examples: lindex {a b {c d e} f} 2 c d e lsort {red green blue} blue green red
  • 16. String Manipulation String manipulation commands: regexp format split string regsub scan join string subcommands compare first last index length match range toupper tolower trim trimleft trimright Note: all indexes start with 0. end means last char • string tolower "THIS" ;# this • string trimleft “XXXXHello” ;# Hello • string index “abcde” 2 ;# c
  • 17. Control Structures C-like in appearance. Just commands that take Tcl scripts as arguments. Commands: if for switch break foreach while eval continue
  • 18. if else set x 2 if {$x < 3} { puts "x is less than 3" } else { puts "x is 3 or more" }
  • 19. while #list reversal set a {a b c d e} set b "” set i [expr [llength $a] - 1] while {$i >= 0} { lappend b [lindex $a $i] incr i -1 } puts $b
  • 20. for and foreach for {set i 0} {$i<10} {incr i} { puts $I } foreach color {red green blue} { puts “I like $color” } set A(1) a; set A(2) b; set A(26) z foreach index [array names A] { puts $A($index) }
  • 21. switch set pete_count 0 set bob_count 0 set other_count 0 foreach name {Peter Peteee Bobus Me Bobor Bob} { switch -regexp $name { ^Pete* {incr pete_count} ^Bob|^Robert {incr bob_count} default {incr other_count} } } puts "$pete_count $bob_count $other_count"
  • 22. Procedures proc command defines a procedure: proc decrement {x} { name expr $x-1 body } list of argument names Procedures behave just like built-in commands: decrement 3 2 Arguments can have default values: proc decrement {x {y 1}} { expr $x-$y } decrement 100 5 ;# 95 decrement 100 ;# 99
  • 23. Procedures Procedures can have a variable number of arguments proc sum args { set s 0 foreach i $args { incr s $i } return $s } sum 1 2 3 4 5 15 sum 0
  • 24. 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 outside "I'm outside" set inside "I'm really outside" proc whereAmI {inside} { global outside puts $outside puts $inside } whereAmI "I wonder where I will be" -> I'm outside I wonder where I will be
  • 25. Tcl File I/O Tcl file I/O commands: open gets seek flush glob close read tell cd fconfigure fblocked fileevent puts source eof pwd filename File commands use 'tokens' to refer to files set f [open "myfile.txt" "r"] => file4 puts $f "Write this text into file" close $f
  • 26. Tcl File I/O 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 => (up to 100 bytes of file $f) 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)
  • 27. Tcl Network I/O socket creates a network connection set f [socket www.sun.com 80] fconfigure $f -buffering line puts $f "GET /" puts [read $f 100] close $f => The 1st 100 characters from Sun's home page Network looks just like a file! To create a server socket, just use socket -server accept portno