Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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”
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
}
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