AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

Tcl Foundations

Tcl programming language: command words and substitution, braced expressions, lists, dictionaries, control flow, procedures, namespaces, explicit file channels and errors. No Tk GUI, Tcl 8.6/9 features or arbitrary script evaluation.

Audience: Learners comfortable saving plain text and invoking an installed interpreter.

Practice: 4 to 6 hours.

Runtime and boundaries: Use installed /usr/bin/tclsh 8.5.9. This old interpreter is recorded teaching evidence, not a deployment recommendation. The accessible web manual is the later 8.5.19 series; actual 8.5.9 execution bounds the claims. Export one entry and its companions into a fresh toy folder. File example 08 creates only Atlas note.txt with exclusive creation and explicit UTF-8/LF, and refuses to overwrite it; the file remains for inspection. Source in example 09 loads only its authored companion. Data is never eval-ed. Tcl open can launch a pipeline for a leading | path; this pack uses fixed filenames. No sockets, exec, native extensions or downloaded packages. A script interpreter and temporary directory are not an arbitrary-code sandbox. Errors are evaluation outcomes, not a separate compiler pass.

Lessons

Commands receive words

A Tcl command is a sequence of words. Whitespace separates words; braces group a literal word, while double quotes permit substitution. A variable value is substituted as one word; its spaces do not become extra arguments. Braced text still has the special backslash-newline rule.

Substitution is not repeated evaluation

Dollar notation reads a variable and square brackets run a command. The result is data at that substitution point, not automatically reparsed as script. list constructs list structure safely. Avoid eval and string-built scripts when ordinary arguments express the operation.

Expressions have their own parser

Use expr with a braced expression so the expression engine sees variables directly and can short-circuit. eq compares strings; == can compare numerically. Integer division floors. Leading-zero integer text may be octal in this version; the bounded decimal contract accepts canonical decimal only.

Lists and dictionaries preserve structure

Use list, lappend, lindex and llength for lists rather than splitting on spaces. A dictionary maps keys to values; dict exists distinguishes absence from a present empty value. dict incr accumulates integer counts. Sort keys explicitly when output order is a contract.

Control flow and procedures

foreach iterates list elements. if, while and for evaluate conditions and bodies; those command arguments have script or expression roles. proc creates local argument variables and returns a value. Default arguments and the final args parameter are different mechanisms.

Namespaces organize trusted code

A namespace qualifies command names and variables. source executes a file as code; it is not a data parser. The module example loads only the included fixed companion beside its entry file and calls a qualified procedure. No package discovery or third-party loading is needed.

Channels need explicit handling

Open fixed toy paths with a declared access mode. CREAT with EXCL refuses an existing file. Set encoding and newline translation explicitly; close the channel even after an operation fails. Character and byte counts differ; these lessons avoid claiming Unicode grapheme correctness.

Observe errors and test boundaries

catch returns a completion code and can capture result and options; nonzero does not always mean an error because return, break and continue also have codes. Return errors with a stable errorcode for contracts. Separate rejected fixtures from successful examples. Tcl 8.5 has no try/finally command.

Reference cards

Assignment: set name value

Store or retrieve a variable.

Literal word: {text with spaces}

Group a word without ordinary substitutions.

Substitution: $name / [command]

Read a variable or substitute a command result.

Expression: expr {$a + $b}

Evaluate fixed arithmetic with braced syntax.

Strings: string length / string equal

Operate on text rather than script source.

List: list / lappend

Build structured elements without manual quoting.

List lookup: lindex / llength

Read an element or count elements.

Dictionary: dict create / dict get

Create and read key-value data.

Presence: dict exists

Distinguish a missing key from its value.

Loop: foreach item $items {...}

Iterate structured list elements.

Procedure: proc name {args} {body}

Define a reusable command with local arguments.

Namespace: namespace eval / name::proc

Organize trusted definitions.

Error: return -code error -errorcode {...}

Return an application error and stable category.

Catch: catch {script} result options

Inspect completion code and details.

File: open path {WRONLY CREAT EXCL}

Create a new file and refuse overwrite.

Channel: fconfigure / close

Set encoding/translation and release the channel.

Supporting configuration: Tcl practice instructions.txt
Use a fresh toy directory and the exact command shown for each example.
File example 08 creates Atlas note.txt exclusively and refuses overwrite.
The module example requires its trusted Study helpers.tcl companion.
No Tcl 8.6 try/finally or modern Tcl features are used.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

Tcl 01 - Words and substitution

The substituted name stays one list element. Braces keep dollar and bracket text literal.

set name {read and code}
puts "Task: $name"
puts {$name [not executed]}
puts [llength [list $name ready]]

Expected:

Task: read and code
$name [not executed]
2

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 01 Words and substitution.tcl'

Expected Tcl evaluation failure: interpreter diagnostic containing missing close-brace. This is an evaluated failure fixture, not a successful program or a separate static compilation pass.

set value {unfinished
Tcl 02 - Braced expressions

Integer and floating division differ. The substituted text is an operand, not an invoked command.

set minutes 20
puts [expr {$minutes * 3}]
puts [expr {5 / 2}]
puts [expr {5 / 2.0}]
set text {[not executed]}
puts [expr {$text eq {[not executed]}}]

Expected:

60
2
2.5
1

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 02 Braced expressions.tcl'

Expected Tcl evaluation failure: interpreter diagnostic containing missing operand. This is an evaluated failure fixture, not a successful program or a separate static compilation pass.

expr {1 +}
Tcl 03 - Structured lists

List construction preserves spaces and punctuation. join is display formatting, not reversible serialization.

set names [list {read notes} {code [small]}]
lappend names {rest & reflect}
puts [llength $names]
puts [lindex $names 1]
puts [join $names { | }]

Expected:

3
code [small]
read notes | code [small] | rest & reflect

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 03 Structured lists.tcl'
Tcl 04 - Dictionaries and presence

An existing empty note differs from an absent key. Sorting makes the printed key order explicit.

set task [dict create name read minutes 20 note {}]
dict incr task minutes 5
puts [dict get $task minutes]
puts [dict exists $task note]
puts [dict exists $task missing]
puts [join [lsort [dict keys $task]] ,]

Expected:

25
1
0
minutes,name,note

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 04 Dictionaries and presence.tcl'

Expected Tcl evaluation failure: interpreter diagnostic containing not known in dictionary. This is an evaluated failure fixture, not a successful program or a separate static compilation pass.

dict get {name read} absent
Tcl 05 - Iterate and branch

The finite authored list and loop bounds make termination explicit. continue skips only the current iteration.

set total 0
foreach value {0 20 40} {
    if {$value == 0} {continue}
    incr total $value
}
set count 0
while {$count < 3} {incr count}
puts "total=$total count=$count"

Expected:

total=60 count=3

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 05 Iterate and branch.tcl'
Tcl 06 - Procedures and arguments

Procedure arguments are local; the caller name is unchanged. The optional argument has a literal default.

proc label {name {minutes 20}} {
    return "$name: $minutes minutes"
}
set name outside
puts [label read]
puts [label code 40]
puts $name

Expected:

read: 20 minutes
code: 40 minutes
outside

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 06 Procedures and arguments.tcl'

Expected Tcl evaluation failure: interpreter diagnostic containing wrong # args. This is an evaluated failure fixture, not a successful program or a separate static compilation pass.

proc pair {a b} {return $a}
pair one
Tcl 07 - Catch a contract error

The contract accepts canonical decimal zero through 120. Leading zeros, signs, whitespace, decimal points and numeric prefixes are intentionally rejected. catch exposes the error without terminating the successful demonstration.

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
set code [catch {minutes 121} message options]
puts "code=$code message=$message"
puts [dict get $options -errorcode]
puts [minutes 120]

Expected:

code=1 message=invalid minutes
ATLAS MINUTES
120

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 07 Catch a contract error.tcl'
Tcl 08 - Create an exclusive toy file

Run in a new toy folder. Only Atlas note.txt is created and retained. A second run refuses to overwrite the existing file; no cleanup command is part of the example.

set out [open {Atlas note.txt} {WRONLY CREAT EXCL}]
set code [catch {
    fconfigure $out -encoding utf-8 -translation lf
    puts $out {read and code}
} message options]
set closed [catch {close $out} closeMessage]
if {$code} {return -options $options $message}
if {$closed} {error $closeMessage}
set input [open {Atlas note.txt} r]
fconfigure $input -encoding utf-8 -translation lf
set text [read $input]
close $input
puts -nonewline $text

Expected:

read and code

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 08 Create an exclusive toy file.tcl'

Generated file (exclusive creation): Atlas note.txt

read and code
Tcl 09 - Load a trusted namespace

source executes the fixed companion as code. file join avoids manually joining path separators; it does not make an arbitrary path trusted.

source [file join [file dirname [info script]] {Study helpers.tcl}]
puts [study::double 20]

Expected:

40

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl 09 Load a trusted namespace.tcl'

Companion file: Study helpers.tcl

namespace eval study {
    proc double {value} {return [expr {$value * 2}]}
}
Tcl exercise A - Validate and total

Each command-line argument is checked before addition. This accepts at most ten canonical decimal values; the empty list totals zero.

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
if {[llength $argv] > 10} {puts stderr {too many values}; exit 2}
set total 0
foreach text $argv {
    if {[catch {minutes $text} value]} {puts stderr $value; exit 2}
    incr total $value
}
puts "total=$total"

Expected:

total=60

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl exercise A Validate and total.tcl' 20 40

Practice: Accept at most ten minutes values from zero through 120; print one total or a diagnostic with status 2.

Tcl exercise B - Count named items

The argument list retains multiword names and dict incr merges duplicates. The output is sorted and deliberately human-readable.

set counts [dict create]
foreach name $argv {dict incr counts $name}
foreach name [lsort [dict keys $counts]] {
    puts "$name: [dict get $counts $name]"
}

Expected:

code: 1
read notes: 2

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl exercise B Count named items.tcl' 'read notes' code 'read notes'

Practice: Count repeated labels while preserving spaces, then print sorted counts.

Tcl exercise C - Four observable cases

The four cases assert both completion code and value. An assertion failure raises an error rather than printing a success count.

proc minutes {text} {
    if {![regexp {^(0|[1-9][0-9]{0,2})$} $text]} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    if {$text > 120} {
        return -code error -errorcode {ATLAS MINUTES} {invalid minutes}
    }
    return [expr {$text + 0}]
}
set passed 0
foreach {input expectedCode expectedValue} {0 0 0 120 0 120 121 1 {invalid minutes} 08 1 {invalid minutes}} {
    set code [catch {minutes $input} value]
    if {$code != $expectedCode || $value ne $expectedValue} {error {test failed}}
    incr passed
}
puts "$passed checks passed"

Expected:

4 checks passed

Run with the supplied authored input:

/usr/bin/tclsh 'Tcl exercise C Four observable cases.tcl'

Practice: Test zero, the upper bound, an out-of-range value and ambiguous leading-zero text.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a bounded local example
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Give original source, companion fixtures, exact invocation and expected stdout, stderr and status. Separate predictions from tests actually executed.
Trace an observed failure
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Reduce the case; distinguish word substitution, data contracts, pattern matches, EOF, timeout and process exit. Separate predictions from tests actually executed.
Test contracts and failures
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Use fixed toy inputs, boundaries and explicit failure categories. Verify unchanged source files and process cleanup. Separate predictions from tests actually executed.
Refactor without changing behavior
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Preserve output, order, status and side effects. Keep data out of generated script strings. Separate predictions from tests actually executed.
Document the execution boundary
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. State interpreter versions, encoding, input limits, trusted files, child lifetimes and platform limits. Separate predictions from tests actually executed.
Explain then practice
For {language}, help with {goal}. Runtime: {runtime}. Constraints: {constraints}. Trace the value or conversation state, then supply an exercise with a separate worked solution. Separate predictions from tests actually executed.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.