Tcl


Documentation


Basics


~ $ tclsh
% set a 2
2
% expr 1 + 2
3
% puts $a
2
% set c [expr $a + 1]  # result of cmd in [ ] is substituted
3
% set d "$a $c"        # var $a and $c is substituted
2 3
% set e {$a $c}        # var $a and $c is not substituted.
$a $c
% set x y
y
% set $x 0
0
% puts $y
0
% while {$c > 1} {set c [expr $c - 1]; puts $c}
2
1
% 

Note that
set c 3; while "$c > 1" {set c [expr $c - 1]; puts $c}
is the same as
set c 3; while "3  > 1" {set c [expr $c - 1]; puts $c}

List


% set x {a b c d}
a b c d
% set y "a b c d"
a b c d
% llength $x
4
% lindex $x 2
c
% lappend x e
a b c d e
% puts $x 
a b c d e

% set x "$x f"
a b c d e f

% foreach i $x {
   puts $i 
}
a
b
c
d
e
f
% foreach {i j} $x {
   puts "$i $j"
}
a b
c d
e f

Array/Hash

~ $ tclsh
% set a(2) 4
4
% set a(1) 2
2
% set a(1000) 2000
2000
% set b(ftp) 21
21
% set b(http) 80
80
% set b(ssh) 22
22
% set a(zero) 0
0
% array name b
http ssh ftp
% array name *p
% array get b
http 80 ssh 22 ftp 21
% foreach {key value} [array get b] {
  puts "$key uses port $value"
}
http uses port 80
ssh uses port 22
ftp uses port 21

Control Structure

% while {$c > 1} {set c [expr $c - 1]; puts $c}
2
1
% for {set x 0} {$x < 10} {incr x} {
  puts $x
}
0
1
2
3
4
5
6
7
8
9
% set x 10
10
% incr x 2
12
% incr x -3
9
% incr x 0.3
expected integer but got "0.3"
% if {$x > 0} {puts "postive"} elseif {$x < 0} {puts "negative"} else {puts "zero"}
postive
% 
% 
% 
% proc factorial {n} {
   set product 1
   for {set i 1} {$i <= $n} {incr i} {
     set product [expr $product*$i]
   }
   return $product
}
% factorial 3
6
% factorial 0
1
% 
% 
% proc callonetime {x} {
   puts $x
   proc callonetime {x} {
     puts "you can only call this proc once!"
   }
}
% callonetime 10
10
% callonetime 10
you can only call this proc once!
% 

Global Variable


% global x
% set x 1
1
% proc foo {} {
  global x
  puts $x
}
% foo
1
% 

Regexp


set VAR "This is a test string"
if {[regexp -nocase [subst -nocommands -nobackslashes {something here:[\s\w]+:$VAR}]} then {
...
}

No comments: