Tcl: Difference between revisions

Content deleted Content added
No edit summary
m 2024 not 2045
 
Line 1:
{{short description|High-level programming language}}
'''Tcl''' (originally from "Tool command language", but nonetheless usually lowercased) is a [[scripting language]] created by [[John Ousterhout]] that is generally thought to be easy to learn, with several [[Lisp]]-like features, without the usual complaints. Some of its features:
{{About||the Chinese electronics company|TCL Technology|other uses|}}
{{Infobox programming language
| name = Tcl
| logo = Tcl-powered.svg
| logo_size = 70px
| logo_alt = Tcl logo
| paradigm = [[multi-paradigm programming language|Multi-paradigm]]: [[event-driven programming|event-driven]], [[functional programming|functional]], [[imperative programming|imperative]], [[object-oriented programming|object-oriented]]
| released = {{Start date and age|1988}}
| designer = [[John Ousterhout]]
| developer = Tcl Core Team<ref name="tclcoreteam" />
| latest release version = {{wikidata|property|preferred|references|edit|Q5288|P348|P548=Q2804309}}
| latest release date = {{ start date and age|{{wikidata|qualifier|preferred|single|Q5288|P348|P548=Q2804309|P577}}}}
| latest preview version = {{wikidata|property|preferred|references|edit|Q5288|P348|P548=Q51930650}}
| latest preview date = {{wikidata|qualifier|preferred|single|Q5288|P348|P548=Q51930650|P577}}
| typing = [[Dynamic typing]], everything is a [[string (programming)|string]]
| implementations = [https://www.activestate.com/activetcl ActiveTcl] [https://www.androwish.org/ Androwish]
| dialects = [http://jim.tcl.tk/ Jim], [https://eagle.to/ Eagle]
| influenced by = [[AWK]], [[Lisp (programming language)|Lisp]]
| influenced = [[PHP]],<ref name="mysqlconference">{{cite web |last=Lerdorf |first=Rasmus |title=PHP on Hormones&nbsp;– history of PHP presentation by Rasmus Lerdorf given at the MySQL Conference in Santa Clara, California | date=2007-04-26 | access-date=2009-12-11 | publisher=The Conversations Network |url=http://itc.conversationsnetwork.org/shows/detail3298.html }}</ref> [[Windows PowerShell|PowerShell]],<ref>{{cite web|url=http://blogs.msdn.com/powershell/archive/2008/05/25/powershell-and-wpf-wtf.aspx|title=PowerShell and WPF: WTF|website=Windows PowerShell Blog|publisher=Microsoft|archive-url=https://web.archive.org/web/20081225093003/http://blogs.msdn.com/powershell/archive/2008/05/25/powershell-and-wpf-wtf.aspx|archive-date=December 25, 2008|url-status=dead|access-date=April 3, 2019}}</ref> [[Tea (programming language)|Tea]], TH1<ref name="th1scripts">{{cite web |title=TH1 Scripts|publisher=Fossil|url=https://fossil-scm.org/home/doc/trunk/www/th1.md }}</ref>
| license = [[BSD licenses|BSD]]-style<ref>{{cite web |url=http://www.tcl-lang.org/software/tcltk/license.html |title= Tcl/Tk License Terms |website=Tcl Developer Xchange |access-date=2016-11-02}}</ref>
| website = {{URL|https://www.tcl-lang.org}}<br />{{URL|https://www.tcl.tk}}
| file_ext = .tcl, .tbc<ref>{{cite web |url=http://docs.activestate.com/tdk/4.1/Compiler.html |title= Tcl Dev Kit – Compiler |website=ActiveState Docs |access-date=2016-11-02}}</ref>
}}
 
'''Tcl''' (pronounced "[[tickle]]" or as an [[initialism]]<ref>{{cite newsgroup|url=https://groups.google.com/d/msg/comp.lang.tcl/4KfTRIr5ZxE/XIw-gnbxIyMJ|first=Kevin|last=Kenny|newsgroup=comp.lang.tcl|title=Re: TCL certification|date=4 July 2005}}</ref>) is a [[High-level programming language|high-level]], [[General-purpose programming language|general-purpose]], [[Interpreter (computing)|interpreted]], [[dynamic programming language]]. It was designed with the goal of being very simple but powerful.<ref>{{cite web |url=http://www.tcl-lang.org/about/language.html |title=Language |website=Tcl Developer Xchange |access-date=2016-11-02}}</ref> Tcl casts everything into the mold of a [[Command (computing)|command]], even programming constructs like variable assignment and procedure definition.<ref>''Tcl Fundamentals'', Chapter 1 in ''Practical Programming in Tcl and Tk'', {{ISBN|0-13-038560-3}}</ref> Tcl supports multiple [[programming paradigm]]s, including [[object-oriented programming|object-oriented]], [[imperative programming|imperative]], [[functional programming|functional]], and [[procedural programming|procedural]] styles.
* Everything is a command, including language structures.
* Everything can be dynamically replaced and overridden.
* All data types can be handled as if they were strings.
* Extremely simple syntactical rules, which everything follows.
* Heavily event-driven.
* Dynamic scope.
* High extensibility.
 
It is commonly used embedded into [[C (programming language)|C]] applications,<ref name="inception" /> for [[rapid application development|rapid prototyping]], scripted applications, GUIs, and testing.<ref>{{cite web |url=http://www.tcl-lang.org/about/uses.html |title=Uses for Tcl/Tk |website=Tcl Developer Xchange |access-date=2016-11-02}}</ref> Tcl interpreters are available for many [[operating system]]s, allowing Tcl code to run on a wide variety of systems. Because Tcl is a very compact language, it is used on [[embedded system]]s platforms, both in its full form and in several other small-footprint versions.<ref>{{cite web |url=http://www.cisco.com/c/en/us/td/docs/ios-xml/ios/ios_tcl/configuration/12-4t/ios-tcl-12-4t-book/nm-script-tcl.html |title=Cisco IOS Scripting with TCL Configuration Guide |website=Cisco Support |access-date=2016-11-02}}</ref>
While Tcl itself does not provide an object oriented framework the language itself can be extended to provide new functionality as that is required. Indeed, many C extensions exist that provide OO funcionality, including the powerful [[XOTcl]] and more traditional [[incr Tcl]]. Some Tcl-based OO extensions also exist.
 
The popular combination of Tcl with the [[Tk (software)|Tk]] extension is referred to as '''Tcl/Tk''' (pronounced "tickle teak" or as an [[initialism]]) and enables building a [[graphical user interface]] (GUI) natively in Tcl. Tcl/Tk is included in the standard [[Python (programming language)|Python]] installation in the form of [[Tkinter]].
The most famous extension is the [[Tk]] toolkit which allows one to write portable [[graphical user interface]]s for a variety of operating systems.
 
== History ==
A simple example, demonstrating event-based computing, follows.
The Tcl programming language was created in the spring of 1988 by [[John Ousterhout]] while he was working at the [[University of California, Berkeley]].<ref>{{cite web |url=http://www.stanford.edu/~ouster/cgi-bin/tclHistory.php |title=History of Tcl |author=John Ousterhout |work=Personal pages |publisher=Stanford University |access-date=2011-08-09}}</ref><ref>{{cite web |url=http://www.tcl-lang.org/about/history.html |title=History of Tcl |website=Tcl Developer Xchange |access-date=2016-11-02}}</ref> Originally "born out of frustration",<ref name="inception">From the inside flap of ''Tcl and the Tk Toolkit'', {{ISBN|0-201-63337-X}}</ref> according to the author, with programmers devising their own languages for extending [[electronic design automation]] (EDA) software and, more specifically, the [[Very Large Scale Integration|VLSI]] design tool [[Magic (software)|Magic]], which was a professional focus for John at the time.<ref>{{Cite web |title=EDA |url=https://wiki.tcl-lang.org/page/EDA |access-date=2022-04-27 |website=wiki.tcl-lang.org}}</ref> Later Tcl gained acceptance on its own. Ousterhout was awarded the [[ACM Software System Award]] in 1997 for Tcl/Tk.<ref>{{cite web | url=http://awards.acm.org/award_winners/ousterhout_1957745.cfm | title=John K Ousterhout – Award Winner | website=ACM Awards | access-date=2016-11-04}}</ref>
 
The name originally comes from '''T'''ool '''C'''ommand '''L'''anguage, but is conventionally written ''Tcl'' rather than ''TCL''.<ref>''From the Tcler's Wiki [http://wiki.tcl.tk/11902 Tcl vs. TCL]''</ref>
----
<pre>
# Simple echo-server that can handle multiple connections.
 
{| class="wikitable"
|-
! Date || Event
|-
| January&nbsp;1990 || Tcl announced beyond Berkeley (Winter [[USENIX]]).
|-
| June&nbsp;1990 || [[Expect]] announced (Summer USENIX).
|-
| January&nbsp;1991 || First announcement of [[Tk (software)|Tk]] (Winter USENIX).
|-
| June&nbsp;1993 || First Tcl/Tk conference (Berkeley). <nowiki>[table]</nowiki> geometry manager (forerunner of <nowiki>[grid]</nowiki>), [[incr Tcl|<nowiki>[incr Tcl]</nowiki>]], TclDP and Groupkit, announced there.
|-
| August&nbsp;1997 || Tcl 8.0 introduced a bytecode compiler.<ref>{{cite web |url=http://www.tcl.tk/software/tcltk/8.0.html |title=Tcl/Tk 8.0 Release Announcement |website=Tcl Developer Xchange |access-date=2014-07-01}}</ref>
|-
| April&nbsp;1999 || Tcl 8.1 introduces full [[Unicode]] support<ref>{{cite web |url=http://www.tcl.tk/software/tcltk/8.1.html |title=Tcl/Tk 8.1 Release Announcement |website=Tcl Developer Xchange |access-date=2014-07-01}}</ref> and advanced [[regular expression]]s.<ref name="regex">{{cite web |url=http://www.tcl.tk/doc/howto/regexp81.html |title=New Regular Expression Features in Tcl 8.1 |website=Tcl Developer Xchange |access-date=2016-11-02}}</ref>
|-
| August&nbsp;1999 || Tcl 8.2 introduces Tcl Extension Architecture (TEA)<ref>{{cite web |url=http://www.tcl.tk/software/tcltk/8.2.html |title=Tcl/Tk 8.2 Release Announcement |website=Tcl Developer Xchange |date=1999-08-18 |access-date=2014-07-01}}</ref>
|-
| August&nbsp;2000 || Tcl Core Team formed, moving Tcl to a more community-oriented development model.<ref name="tclcoreteam">{{cite web |url=http://www.tcl.tk/community/coreteam |title=Tcl/Tk Core Development |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref>
 
|-
proc newConnection {sock addr port} {
| September&nbsp;2002 || Ninth Tcl/Tk conference (Vancouver). Announcement of starkit packaging system. Tcl 8.4.0 released.<ref>{{cite web |url=http://www.tcl.tk/software/tcltk/8.4.html |title=Tcl/Tk 8.4 Release Announcement |website=Tcl Developer Xchange |date=2013-06-01 |access-date=2014-07-01}}</ref>
fconfigure $sock -blocking no -buffering line
|-
| December&nbsp;2007 || Tcl 8.5 added new datatypes, a new extension repository, [[Arbitrary-precision arithmetic|bignums]],<ref>{{cite web |url=http://www.tcl.tk/cgi-bin/tct/tip/237.html |title=TIP #237: Arbitrary-Precision Integers for Tcl |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref> [[Anonymous function|lambdas]].<ref>{{cite web |url=http://www.tcl.tk/cgi-bin/tct/tip/194.html |title=TIP #194: TIP #194: Procedures as Values via apply |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref><ref>{{cite web |url=http://www.tcl.tk/software/tcltk/8.5.html |title=Tcl/Tk 8.5 Release Announcement |website=Tcl Developer Xchange |date=2013-09-18 |access-date=2014-07-01}}</ref>
|-
| December&nbsp;2012 || Tcl 8.6 added built-in dynamic object system, TclOO, and stackless evaluation.<ref name="tcl86release">{{cite web |url=http://www.tcl.tk/software/tcltk/8.6.html |title=Tcl/Tk 8.6 Release Announcement |website=Tcl Developer Xchange |date=2013-09-20 |access-date=2014-07-01}}</ref>
|-
| September&nbsp;2024 || Tcl 9.0 added 64-bit capabilities, support for the full Unicode code point range, uses [[epoll]] & [[kqueue]]<ref name="tcl90release">{{cite web |url=https://www.tcl-lang.org/software/tcltk/9.0.html |title=Tcl/Tk 9.0 Release Announcement |website=Tcl Developer Xchange |date=2024-09-26 |access-date=2024-09-26}}</ref>
 
|}
# handleData should be called with $sock as the parameter when data can
# be read from the socket
fileevent $sock readable "handleData $sock"
 
Tcl conferences and workshops are held in both the United States and Europe.<ref>{{cite web |url=https://www.tcl.tk/community/conferences.html |title=Tcl/Tk Conferences |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref>
return
}
 
== Features ==
[[File:Eclipse-dltk-itcl en fedora 11 con KDE 4.2.4.png|thumb|right|250px|A Tcl file being edited in the [[Eclipse (software)|Eclipse]] IDE]]
Tcl's features include
* All operations are [[command (computing)|commands]], including language structures. They are written in [[prefix notation]].
* Commands commonly accept a variable number of arguments (are [[variadic]]).
* Everything can be dynamically redefined and overridden. Actually, there are no keywords, so even control structures can be added or changed, although this is not advisable.
* All [[data type]]s can be manipulated as [[string (computer science)|strings]], including [[source code]]. Internally, variables have types like integer and double, but converting is purely automatic.
* Variables are not declared, but assigned to. Use of a non-defined variable results in an error.
* Fully dynamic, class-based [[object-oriented programming|object system]], TclOO, including advanced features such as meta-classes, filters, and [[mixin]]s.<ref name="tip257">{{cite web |url=http://www.tcl.tk/cgi-bin/tct/tip/257.html |title=TIP #257: Object Orientation for Tcl |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref>
* [[Event-driven programming|Event-driven interface]] to [[network socket|sockets]] and [[computer file|files]]. Time-based and user-defined events are also possible.
* Variable visibility restricted to lexical (static) [[scope (computer science)|scope]] by default, but <code>uplevel</code> and <code>upvar</code> allowing procs to interact with the enclosing functions' scopes.
* All commands defined by Tcl itself generate error messages on incorrect usage.
* [[Extensibility]], via [[C (programming language)|C]], [[C++]], [[Java (programming language)|Java]], Python, and Tcl.
* [[Interpreted language]] using [[bytecode]]
* Full [[Unicode]] (3.1 in the beginning, regularly updated) support, first released 1999.
* [[Regular expression]]s<ref name="regex" />
* [[Cross-platform]]: [[Windows API]]; [[Unix]], [[Linux]], [[Macintosh]] etc.
* Close, cross-platform integration with windowing ([[GUI]]) interface [[Tk (software)|Tk]].
* Multiple distribution mechanisms exist:
** Full development version (for Windows e.g. [https://www.activestate.com/ActiveTcl ActiveState Tcl], see [https://www.tcl.tk/software/tcltk/])
** [http://wiki.tcl.tk/52 Tclkits] (single file executable containing a complete scripting runtime, only about 4 megabytes in size), [http://wiki.tcl.tk/52 Starkits] (wrapping mechanism for delivering an application in a self-contained, installation-free, and highly portable way) and [http://wiki.tcl.tk/52 Starpacks] (combine Starkit with Tclkit to produce a Starpack – a single platform specific executable file, ideal for easy deployment)
** [http://jim.tcl.tk/ The Jim Interpreter], a small footprint Tcl implementation
** Freely distributable [[source code]] under a [[BSD license]].<ref>{{cite web |url=http://www.tcl.tk/software/tcltk/download.html |title=Download Tcl/Tk Sources |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref>
 
=== Safe-Tcl ===
proc handleData {sock} {
Safe-Tcl is a subset of Tcl that has restricted features so that Tcl scripts cannot harm their hosting machine or application.<ref>{{cite web |url=http://www.tcl.tk/software/plugin/safetcl.html |title=Safe Tcl |website=Tcl Developer Xchange |access-date=2016-11-01}}</ref> File system access is limited and arbitrary system commands are prevented from execution. It uses a dual interpreter model with the untrusted interpreter running code in an untrusted script. It was designed by [[Nathaniel Borenstein]] and [[Marshall Rose]] to include active messages in e-mail. Safe-Tcl can be included in e-mail when the ''application/safe-tcl'' and ''multipart/enabled-mail'' are supported. The functionality of Safe-Tcl has since been incorporated as part of the standard Tcl/Tk releases.<ref>{{cite conference | first=Lawrie |last=Brown |date=September 18–20, 1996 |page=50 |editor1-first=Terry|editor1-last=Bossomaier |editor2-first=Lucy|editor2-last=Chubb |title=Mobile Code Security |location=Melbourne, Australia |book-title=Proceedings, 2nd Joint Conference, AUUG '96 and Asia-Pacific WWW '96 | url=https://books.google.com/books?id=LP5CKyrp9WsC&pg=PA50 |access-date=2011-03-22 }}</ref><ref>{{cite book |author1=Welch, Brent B. |author2=Jones, Ken |author3=Hobbs, Jeffrey |year=2003 |page=291 |title=Practical programming in Tcl and Tk | volume=1 |edition=4th |publisher=Prentice Hall PTR |isbn=0-13-038560-3 }}</ref>
set line [gets $sock]
 
if {($line == "") && [eof $sock]} {
== Syntax and fundamental semantics ==
close $sock
The syntax and semantics of Tcl are covered by twelve rules<ref>{{cite web |url=http://www.tcl.tk/man/tcl/TclCmd/Tcl.htm |title=Tcl manual page – Tcl Built-In Commands |website=Tcl Developer Xchange |access-date=2014-06-14}}</ref> known as the Dodekalogue.<!-- do not "correct" this spelling --><ref>{{cite web |url=http://wiki.tcl.tk/10259 |title=Dodekalogue |publisher=Tcler's Wiki |access-date=2014-06-14}} (Also contains a shorter "Octalogue" version of the rules.)</ref>
} else {
 
puts $sock $line
A Tcl script consists of a series of command invocations. A command invocation is a list of words separated by whitespace and terminated by a [[newline]] or semicolon. The first word is the name of a command, which may be built into the language, found in an available [[Library (computing)|library]], or defined in the script itself. The subsequent words serve as arguments to the command:
 
commandName argument1 argument2 ... argumentN
 
The following example uses the ''puts'' (short for "put string") command to display a string of text on the host console:
 
<syntaxhighlight lang="Tcl">
puts "Hello, World!"
</syntaxhighlight>
 
This sends the string "Hello, World!" to the [[Standard streams#Standard output (stdout)|standard output]] device along with an appended newline character.
 
Variables and the results of other commands can be substituted into strings, such as in this example which uses the ''set'' and ''expr'' commands to store the result of a calculation in a variable (note that Tcl does not use <code>=</code> as an assignment operator), and then uses ''puts'' to print the result together with some explanatory text:
 
<syntaxhighlight lang="Tcl">
# expr evaluates text string as an expression
set sum [expr 1+2+3+4+5]
puts "The sum of the numbers 1..5 is $sum."
</syntaxhighlight>
 
The <code>#</code> character introduces a [[Comment (computer programming)|comment]]. Comments can appear anywhere the interpreter is expecting a command name.
 
<syntaxhighlight lang="Tcl">
# with curly braces, variable substitution is performed by expr
set x 1
set sum [expr {$x + 2 + 3 + 4 + 5}]; # $x is not substituted before passing the parameter to expr;
# expr substitutes 1 for $x while evaluating the expression
puts "The sum of the numbers 1..5 is $sum."; # sum is 15
</syntaxhighlight>
 
<syntaxhighlight lang="Tcl">
# without curly braces, variable substitution occurs at the definition site (lexical scoping)
set x 2
set op *
set y 3
set res [expr $x$op$y]; # $x, $op, and $y are substituted, and the expression is evaluated to 6
puts "$x $op $y is $res."; # $x, $op, $y, and $res are substituted and evaluated as strings
</syntaxhighlight>
 
As seen in these examples, there is one basic construct in the language: the command. Quoting mechanisms and substitution rules determine how the arguments to each command are processed.
 
One special substitution occurs ''before'' the parsing of any commands or arguments. If the final character on a line (i.e., immediately before a newline) is a backslash, then the backslash-newline combination (and any spaces or tabs immediately following the newline) are replaced by a single space. This provides a [[line continuation]] mechanism, whereby long lines in the source code can be wrapped to the next line for the convenience of readers.
 
Continuing with normal argument processing, a word that begins with a double-quote character (<code>"</code>) extends to the next double-quote character. Such a word can thus contain whitespace and semicolons without those characters being interpreted as having any special meaning (i.e., they are treated as normal text characters). A word that begins with an opening curly-brace character (<code>{</code>) extends to the next closing curly-brace character (<code>}</code>). Inside curly braces all forms of substitution are suppressed except the previously mentioned backslash-newline elimination. Words not enclosed in either construct are known as bare words.
 
In bare and double-quoted words, three types of substitution may occur:
* '''Command substitution''' replaces the contents of balanced square brackets with the result of evaluating the script contained inside. For example, <code>[expr 1+2+3]</code> is replaced by the result of evaluating the contained expression (in this case 6).
* '''Variable substitution''' replaces the name of a variable prefixed with a dollar sign with the contents (or value) of the variable. For example, <code>$foo</code> is replaced by the contents of the variable called "foo". The variable name may be surrounded by curly braces to separate it from subsequent text in otherwise ambiguous cases (e.g., <code>${foo}ing</code>).
* '''Backslash substitution''' replaces a backslash followed by a letter with another character. For example, <code>\n</code> is replaced by a newline.
Substitution proceeds left-to-right in a single scan through each word. Any substituted text will not be scanned again for possible further substitutions. However, any number of substitutions can appear in a single word.
 
From Tcl 8.5 onwards, any word may be prefixed by <code>{*}</code>, which causes the word to be split apart into its constituent sub-words for the purposes of building the command invocation (similar to the <code>,@</code> sequence of [[Lisp (programming language)|Lisp]]'s quasiquote feature).
 
As a consequence of these rules, the result of any command may be used as an argument to any other command. Note that, unlike in [[Bourne shell|Unix command shells]], Tcl does not reparse any string unless explicitly directed to do so, which makes interactive use more cumbersome, but scripted use more predictable (e.g., the presence of spaces in filenames does not cause difficulties).
 
The single equality sign (<code>=</code>) serves no special role in the language at all. The double equality sign (<code>==</code>) is the test for equality which is used in expression contexts such as the <code>expr</code> command and in the first argument to <code>if</code>. (Both commands are part of the standard library; they have no special place in the library and can be replaced if desired.)
 
The majority of Tcl commands, especially in the standard library<!--89/128 from 8.6a2 documentation-->, are [[Variadic function|variadic]], and the <code>proc</code> (the constructor for scripted command procedures) allows one to define default values for unspecified arguments and a catch-all argument to allow the code to process arbitrary numbers of arguments.
 
Tcl is not statically typed: each variable may contain integers, floats, strings, lists, command names, dictionaries, or any other value; values are reinterpreted (subject to syntactic constraints) as other types on demand. However, values are [[Immutable object|immutable]] and operations that appear to change them actually just return a new value instead.
 
=== Basic commands ===
The most important commands that refer to program execution and data operations are:
* <code>set</code> writes a new value to a variable (creates a variable if did not exist). If used only with one argument, it returns the value of the given variable (it must exist in this case).
* <code>proc</code> defines a new command, whose execution results in executing a given Tcl script, written as a set of commands. <code>return</code> can be used to immediately return control to the caller.
 
The usual execution control commands are:
* <code>[[if-then-else|if]]</code> executes given script body (second argument), if the condition (first argument) is satisfied. It can be followed by additional arguments starting from <code>elseif</code> with the alternative condition and body, or <code>else</code> with the complementary block.
* <code>[[While loop#Tcl|while]]</code> repeats executing given script body, as long as the condition (first argument) remains satisfied
* <code>[[Foreach#Tcl|foreach]]</code> executes given body where the control variable is assigned list elements one by one.
* <code>for</code> shortcut for initializing the control variable, condition (as in <code>while</code>) and the additional "next iteration" statement (command executed after executing the body)
 
Those above looping commands can be additionally controlled by the following commands:
* <code>break</code> interrupts the body execution and returns from the looping command
* <code>continue</code> interrupts the body execution, but the control is still given back to the looping command. For <code>while</code> it means to loop again, for <code>for</code> and <code>foreach</code>, pick up the next iteration.
* <code>return</code> interrupts the execution of the current body no matter how deep inside a procedure, until reaching the procedure boundary, and returns given value to the caller.
 
=== Advanced commands ===
* <code>expr</code> passes the argument to a separate expression interpreter and returns the evaluated value. Note that the same interpreter is used also for "conditional" expression for <code>if</code> and looping commands.
* <code>list</code> creates a [[list (computer science)|list]] comprising all the arguments, or an empty string if no argument is specified. The <code>lindex</code> command may be used on the result to re-extract the original arguments.
* <code>array</code> manipulates [[Associative array|array]] variables.
* <code>dict</code> manipulates [[Associative array|dictionary]] (since 8.5), which are lists with an even number of elements where every two elements are interpreted as a key/value pair.
* <code>regexp</code> matches a regular expression against a string.
* <code>regsub</code> Performs substitutions based on regular expression pattern matching.
* <code>[[Tcl#Uplevel|uplevel]]</code> is a [[Command (computing)|command]] that allows a command script to be executed in a [[Scope (computer science)|scope]] other than the current innermost scope on the stack.
* <code>[[Tcl#Upvar|upvar]]</code> creates a link to variable in a different stack frame.
* <code>namespace</code> lets you create, access, and destroy separate contexts for commands and variables.
* <code>apply</code> applies an anonymous function (since 8.5).
* <code>coroutine</code>, <code>yield</code>, and <code>yieldto</code> create and produce values from [[coroutine]]s (since 8.6).
* <code>try</code> lets you trap and process errors and exceptions.
* <code>catch</code> lets you trap exceptional returns.
* <code>zlib</code> provides access to the compression and checksumming facilities of the Zlib library (since 8.6).
 
=== Uplevel ===
<code>uplevel</code> allows a command script to be executed in a [[Scope (computer science)|scope]] other than the current innermost scope on the stack. Because the command script may itself call procedures that use the ''uplevel'' command, this has the net effect of transforming the [[call stack]] into a call tree.<ref>{{cite web |url=http://www.tcl.tk/man/tcl8.6/TclCmd/uplevel.htm |title=uplevel manual page – Built-In Commands |website=Tcl Developer Xchange |access-date=2016-06-14}}</ref>
 
It was originally implemented to permit Tcl procedures to reimplement built-in commands (like ''for'', ''if'' or ''while'') and still have the ability to manipulate local [[Variable (computer science)|variables]]. For example, the following Tcl script is a reimplementation of the ''for'' command (omitting [[exception handling]]):
 
<syntaxhighlight lang="tcl">
proc for {initCmd testExpr advanceCmd bodyScript} {
uplevel 1 $initCmd
set testCmd [list expr $testExpr]
while {[uplevel 1 $testCmd]} {
uplevel 1 $bodyScript
uplevel 1 $advanceCmd
}
}
</syntaxhighlight>
 
=== Upvar ===
return
<code>upvar</code> arranges for one or more [[local variable]]s in the current procedure to refer to variables in an enclosing procedure call or to [[global variable]]s. The upvar command simplifies the implementation of call-by-name procedure calling and also makes it easier to build new control constructs as Tcl procedures.<ref>{{cite web |url=http://www.tcl.tk/man/tcl8.6/TclCmd/upvar.htm |title=upvar manual page – Built-In Commands |website=Tcl Developer Xchange |access-date=2016-06-14}}</ref>
 
A decr command that works like the built-in <code>incr</code> command except it subtracts the value from the variable instead of adding it:
 
<syntaxhighlight lang="tcl">
proc decr {varName {decrement 1}} {
upvar 1 $varName var
incr var [expr {-$decrement}]
}
</syntaxhighlight>
 
=== Object-oriented ===
{{See also|Object-oriented programming}}
Tcl 8.6 added a built-in dynamic object system, TclOO, in 2012.<ref name="tip257" /> It includes features such as:
* Class-based object system. This is what most programmers expect from OO.
* Allows per-object customization and dynamic redefinition of classes.
* Meta-classes
* Filters
* Mixins
* A system for implementing methods in custom ways, so that package authors that want significantly different ways of doing a method implementation may do so fairly simply.
 
<syntaxhighlight lang="Tcl">
oo::class create fruit {
method eat {} {
puts "yummy!"
}
}
oo::class create banana {
superclass fruit
constructor {} {
my variable peeled
set peeled 0
}
method peel {} {
my variable peeled
set peeled 1
puts "skin now off"
}
method edible? {} {
my variable peeled
return $peeled
}
method eat {} {
if {![my edible?]} {
my peel
}
next
}
}
set b [banana new]
$b eat → prints "skin now off" and "yummy!"
fruit destroy
$b eat → error "unknown command"
</syntaxhighlight>
 
Tcl did not have [[object-oriented programming|object oriented]] (OO) syntax until 2012,<ref name="tip257" /> so various extension packages emerged to enable object-oriented programming. They are widespread in existing Tcl source code. Popular extensions include:
* [[incr Tcl]]
* [[XOTcl]]
* [[Itk]]
* Snit
* [http://jfontain.free.fr/stooop.html STOOOP]
 
TclOO was not only added to build a strong object oriented system, but also to enable extension packages to build object oriented abstractions using it as a foundation. After the release of TclOO, [[incr Tcl]] was updated to use TclOO as its foundation.<ref name="tcl86release" />
 
== Web application development ==
[http://www.tcl.tk/software/tclhttpd/ Tcl Web Server] is a pure-Tcl implementation of an HTTP protocol server. It runs as a script on top of a vanilla Tcl interpreter.
 
[https://tcl.apache.org/rivet/ Apache Rivet] is an open source programming system for [[Apache HTTP Server]] that allows developers to use Tcl as a scripting language for creating dynamic web applications. Rivet is similar to [[PHP]], [[Active Server Pages|ASP]], and [[JavaServer Pages|JSP]]. Rivet was primarily developed by Damon Courtney, David Welton, Massimo Manghi, Harald Oehlmann and [[Karl Lehenbauer]]. Rivet can use any of the thousands of publicly available Tcl packages that offer countless features such as database interaction (Oracle, PostgreSQL, MySQL, SQLite, etc.), or interfaces to popular applications such as the [[GD Graphics Library]].
 
== Interfacing with other languages ==
Tcl interfaces natively with the [[C (programming language)|C]] language.<ref name="tclcapi">{{cite web |url=https://www.tcl.tk/man/tcl/TclLib/contents.htm |title=Tcl C API |website=tcl.tk |access-date=2016-11-02}}</ref> This is because it was originally written to be a framework for providing a syntactic front-end to commands written in C, and all commands in the language (including things that might otherwise be [[keyword (computer programming)|keywords]], such as <code>if</code> or <code>while</code>) are implemented this way. Each command implementation [[Subroutine|function]] is passed an array of values that describe the (already substituted) arguments to the command, and is free to interpret those values as it sees fit.
 
Digital [[logic simulation|logic simulators]] often include a Tcl scripting interface for simulating [[Verilog]], [[VHDL]] and SystemVerilog [[hardware description language|hardware languages]].
 
Tools exist (e.g. [[SWIG]], [http://elf.org/ffidl Ffidl]) to automatically generate the necessary code to connect arbitrary C functions and the Tcl runtime, and [http://equi4.com/starkit/critcl.html Critcl] does the reverse, allowing embedding of arbitrary C code inside a Tcl script and compiling it at runtime into a [[Dynamic-link library|DLL]].
 
== Extension packages ==
The Tcl language has always allowed for extension packages, which provide additional functionality, such as a GUI, terminal-based application automation, database access, and so on. Commonly used extensions include:
 
; Tk: The most popular Tcl extension is the [[Tk (software)|Tk]] toolkit, which provides a [[graphical user interface]] library for a variety of [[operating system]]s. Each GUI consists of one or more ''frames''. Each frame has a layout manager.
; Expect: One of the other very popular Tcl extensions is [[Expect]] extension. The early close relationship of Expect with Tcl is largely responsible for the popularity of Tcl in prolific areas of use such as in Unix testing, where Expect was (and still is today) employed very successfully to automate telnet, ssh, and serial sessions to perform many repetitive tasks (i.e., scripting of formerly interactive-only applications). Tcl was the only way to run Expect, so Tcl became very popular in these areas of industry.
; Tile/Ttk: Tile/Ttk<ref name="tktable1208">{{cite web |url=http://tktable.sourceforge.net/tile |title=Tile: an improved themeing engine for Tk |website=SourceForge |access-date=August 7, 2016}}</ref> is a styles and theming widget collection that can replace most of the widgets in Tk with variants that are truly platform native through calls to an [[operating system]]'s [[API]]. Themes covered in this way are [[Windows XP]], Windows Classic, [[Qt (toolkit)|Qt]] (that hooks into the [[X11]] [[KDE]] environment libraries) and [[Aqua (user interface)|Aqua]] (Mac OS X). A theme can also be constructed without these calls using widget definitions supplemented with image [[pixmap]]s. Themes created this way include Classic Tk, Step, Alt/Revitalized, Plastik and Keramik. Under Tcl 8.4, this package is known as Tile, while in Tcl 8.5 it has been folded into the core distribution of Tk (as Ttk).
; Tix: Tix, the Tk Interface eXtension, is a set of user interface components that expand the capabilities of Tcl/Tk and Python applications. It is an open source software package maintained by volunteers in the Tix Project Group and released under a BSD-style license.<ref name="tixlic96">{{cite web |url=http://tix.sourceforge.net/license.terms |title=Tix License |publisher=SourceForge|access-date=August 7, 2012}}</ref>
; Itcl/IncrTcl: [[Itcl]] is an object system for Tcl, and is normally named as [incr Tcl] (that being the way to increment in Tcl, similar in fashion to the name C++).
; Tcllib: [[Tcllib]] is a set of scripted packages for Tcl that can be used with no compilation steps.
; Tklib: Tklib is a collection of utility modules for Tk, and a companion to Tcllib.
; tDOM: tDOM is a Tcl extension for parsing XML, based on the [[Expat (library)|Expat]] parser
; TclTLS: TclTLS is [[OpenSSL]] extension to Tcl.
; TclUDP: The TclUDP<ref name="tcludp1109">{{cite web |url=http://wiki.tcl.tk/8493 |title=TclUDP |publisher=Tcl'ers Wiki |access-date=August 7, 2012}}</ref> extension provides a simple library to support [[User Datagram Protocol]] (UDP) sockets in Tcl.
; TWAPI: TWAPI (Tcl Windows API) is an extension to Tcl providing bindings to the Windows API.
; Databases: Tcl Database Connectivity (TDBC), part of Tcl 8.6, is a common database access interface for Tcl scripts. It currently supports drivers for accessing [[MySQL]], [[ODBC]], [[PostgreSQL]] and [[SQLite]] databases. More are planned for the future. Access to databases is also supported through database-specific extensions, of which there are many available.<ref name="tdbc1202">{{cite web |url=http://wiki.tcl.tk/20343 |title=TDBC |publisher=Tcl'ers Wiki |access-date=August 7, 2012}}</ref>
 
== See also ==
{{Portal|Computer programming}}
* [[Eggdrop]]
* [[Expect]]
* [[TclX]]
* [[Tkdesk]]
* [[Comparison of integrated development environments#Tcl|Comparison of Tcl integrated development environments]]
* [[Comparison of programming languages]]
* [[List of programming languages]]
* [[Environment Modules (software)#modulefiles|Environment Modules]]
 
== References ==
{{Reflist|30em}}
 
== Further reading ==
{{Refbegin}}
* {{cite book |last1=Ousterhout |first1=John K. |author-link1=John Ousterhout |last2=Jones |first2=Ken |title=Tcl and the Tk Toolkit |year=2009 |publisher=Addison Wesley |isbn=978-0-321-33633-0 |url=http://www.informit.com/store/tcl-and-the-tk-toolkit-9780321336330 |edition=2nd |access-date=4 November 2012}}
* {{cite book |last=Foster-Johnson |first=Eric |title=Graphical Applications with Tcl & Tk |year=1997 |publisher=M&T Books |location=New York, N.Y. |isbn=1-55851-569-0 |url=https://archive.org/details/graphicalapplica00fost |edition=2nd |access-date=4 November 2012 }}
* Brent B. Welch, ''[http://beedub.com/book Practical Programming in Tcl and Tk]'', [[Prentice Hall]], Upper Saddle River, NJ, USA, {{ISBN|0-13-038560-3}}, 2003
* J Adrian Zimmer, ''[http://www.jazimmer.net/tclbook/home.html Tcl/Tk for Programmers]'', [[IEEE Computer Society]], distributed by John Wiley and Sons, {{ISBN|0-8186-8515-8}}, 1998
* Mark Harrison and Michael McLennan, ''[http://www.informit.com/store/effective-tcl-tk-programming-writing-better-programs-9780201634747 Effective Tcl/Tk Programming]'', [[Addison-Wesley]], Reading, MA, USA, {{ISBN|0-201-63474-0}}, 1998
* Bert Wheeler, ''[http://www.packtpub.com/tcl-tk-8-5-programming-cookbook/book Tcl/Tk 8.5 Programming Cookbook]'', [[Packt Publishing]], Birmingham, England, UK, {{ISBN|1849512981}}, 2011
* Wojciech Kocjan, Piotr Beltowski ''[http://www.packtpub.com/tcl-8-5-network-programming/book Tcl 8.5 Network Programming]'', [[Packt Publishing]], {{ISBN|1849510962}}, 2010
* Clif Flynt ''Tcl/Tk, Third Edition: A Developer’s Guide'', {{ISBN|0123847176}}, 2012
* Ashok P. Nadkarni ''The Tcl Programming Language'', {{ISBN|154867964X}}, 2017
{{Refend}}
 
== External links ==
{{Wikibooks|Tcl Programming}}
{{Commons category|Tcl programming language family}}
* {{Official website}}
* [http://core.tcl.tk/ Tcl Sources], main Tcl and Tk source code download website
* [http://wiki.tcl.tk/ Tcler's Wiki]
* [http://www.tkdocs.com/ TkDocs]
 
{{Programming languages}}
{{FOSS}}
 
{{Authority control}}
 
[[Category:American inventions]]
socket -server newConnection 20000
[[Category:Cross-platform free software]]
vwait forever
[[Category:Cross-platform software]]
</pre>
[[Category:Dynamically typed programming languages]]
----
[[Category:Free compilers and interpreters]]
See [http://www.faqs.org/faqs/tcl-faq/ Tcl FAQ], [http://mini.net/tcl/ Tcl'ers Wiki], [http://www.neosoft.com/tcl/ Tcl Contributed Sources Archive], [[Programming language]].
[[Category:Free software programmed in C]]
[[Category:High-level programming languages]]
[[Category:Multi-paradigm programming languages]]
[[Category:Object-oriented programming languages]]
[[Category:Procedural programming languages]]
[[Category:Programming languages created in 1988]]
[[Category:Scripting languages]]
[[Category:Tcl programming language family]]
[[Category:Text-oriented programming languages]]
[[Category:Homoiconic programming languages]]