Tcl Basics¶
0. Overview¶
Tcl stand for Tool Command Language. It is a small, dymanic scripting language designed to be easy to embed and automate. It is widely know for:
- Simple syntax
- Strong string handling
- Dynamic typing
- Command-based structure
- Use with Tk for GUIs
1. Installation¶
To install Tcl you need to run:
2. Mental Model¶
A Tcl program is made of commands.
This means:
- command name:
puts - argument: "Hello, world"
Another example:
setassigns a variable$namereads a variable
3. Basic Syntax¶
Words and commands¶
A command is usually one line:
You can also separete commands with ;:
Variable substitution with $¶
Command substitution []¶
The result of a command can be inserted into another command:
Grouping with braces {}¶
Braces usually prevent substitution:
this prints $x, not 5.
Grouping with quoutes ""¶
Quotes allow substitution:
4. Variables¶
Change a variable:
Unset it:
5. Lists¶
Lists are gundamental in Tcl.
Useful list commands:
Example:
6. Math¶
Use expr for arithmetic.
Use braces with expr:
That is the normal safe style.
7. Strings¶
Common string commands:
string lengthstring toupperstring tolowerstring trimstring firststring range
8. Conditionals¶
elseif works too:
9. Loops¶
while¶
for¶
foreach¶
10. Procedures¶
Procedures are functions.
Return a value:
11. Scope¶
Variables inside a procedure are local by default.
If you need a global variable:
12. Arrays¶
Tcl arrays are key-value maps.
Loop over keys:
13. Dictionaries¶
Modern Tcl often uses dictionaries.
Update:
14. File I/O¶
Write a file:
Read a file:
15. Comments¶
16. Mini Cheat Sheet¶
set x 10
puts $x
puts [expr {$x + 5}]
if {$x > 5} {
puts "yes"
}
foreach item {a b c} {
puts $item
}
proc square {n} {
return [expr {$n * $n}]
}
puts [square 4]
17. Documentation-Style Summary¶
Core concepts:
- Syntax is command + arguments.
- Variables use
$name. - Command results use
[command ...]. - Braces
{}suppress substitution. - Quotes
""allow substitution. - Arithmetic goes through
expr. - Functions are defined with
proc. - Lists, arrays, and dictionaries are key data tools.
Reference Material¶
Websites