TCL QuickSheet

tclsh ?fileName arg arg ...?

  Crunch Bang Shell Exec Example:
  #!/bin/sh
  # the next line restarts using tclsh \
  exec tclsh "$0" "$@" 
Variables
  $name or ${name} : where name identifies a scalar variable
  $name(index)     : where name identifies an array (hash table) name.

Reserved Arrays and Variables
  $argc : arg count  $argv : arglist     $arg0 : script-filename

  $env(LOGIN)        $env(SYS_FOLDER)    $env(APPLE_M_FOLDER)  $env(PRINT_MON_FOLDER)
  $env(USER)         $env(EXT_FOLDER)    $env(PREF_FOLDER)     $env(SHARED_TRASH_FOLDER)
  $env(PWD)          $env(CP_FOLDER)     $env(STARTUP_FOLDER)  $env(DESK_FOLDER)

  $errorCode         errorCode format:
                     ARITH code msg      CHILDKILLED pid sigName msg
                     POSIX errName msg   CHILDSTATUS pid code
                     NONE                CHILDSUSP pid code

  $errorInfo         $tcl_library        $tcl_patchLevel       $tclpkgPath

  $tcl_platform(byteOrder)               $tcl_platform(debug)
  $tcl_platform(machine)                 $tcl_platform(os)
  $tcl_platform(osVersion)               $tcl_platform(platform)
  $tcl_platform(threaded)                $tcl_platform(user)

  $tcl_prompt1 : primary prompt          $tcl_prompt2 : line-continuation prompt

  $tcl_precision     $tcl_rcFileName     $tcl_rcRsrcName       $tcl_traceCompile
  $tcl_traceExec     $tcl_wordchars      $tcl_nonwordchars     $tcl_version

variable manipulation commands

  • global – Access global variables
  • array – Manipulate array variables
  • set – Read and write variables
  • unset – Delete variables

list manipulation commands

  • concat – Join lists together
  • join – Create a string by joining together list elements
  • lappend – Append list elements onto a variable
  • lindex – Retrieve an element from a list
  • linsert – Insert elements into a list
  • list – Create a list
  • llength – Count the number of elements in a list
  • lrange – Return one or more adjacent elements from a list
  • lreplace – Replace elements in a list with new elements
  • lsearch – See if a list contains a particular element
  • lsort – Sort the elements of a list
  • parray – Print array
  • tcl_endOfWord
  • tcl_startOfNextWord
  • tcl_startOfPreviousWord
  • tcl_wordBreakAfter
  • tcl_wordBreakBefore

string manipulation commands

  • append – Append to variable
  • incr – Increment the value of a variable
  • regexp – Match a regular expression against a string
  • regsub – Perform substitutions based on regular expression pattern matching
  • binary – Insert and extract fields from binary strings
  • scan – Parse string using conversion specifiers in the style of sscanf
  • subst – Perform backslash, command, and variable substitutions

structure commands

  • eval – Evaluate a Tcl script
  • error – Generate an error
  • namespace – create and manipulate contexts for commands and variables
  • proc – Create a Tcl procedure
  • rename – Rename or delete a command
  • return – Return from a procedure
  • uplevel – Execute a script in a different stack frame
  • unknown – Handle attempts to use non-existent commands

logical control commands

  • break – Abort looping command
  • continue – Skip to the next iteration of a loop
  • for – “For” loop
  • foreach – Iterate over all elements in one or more lists
  • if – Execute scripts conditionally
  • switch – Evaluate one of several scripts, depending on a given value
  • while – Execute script repeatedly as long as a condition is

file and directory commands

  • pwd – Return the current working directory
  • cd – Change working directory
  • file – Manipulate file names and attributes
  • fileevent – Execute a script when a channel becomes readable or writable
  • glob – Return names of files that match patterns

channel manipulation commands

  • close – Close an open channel
  • eof – Check for end of file condition on channel
  • fblocked – Test whether the last input operation exhausted all available input
  • fconfigure – Set and get options on a channel
  • fcopy – Copy data from one channel to another
  • flush – Flush buffered output for a channel
  • gets – Read a line from a channel
  • open – Open a file-based or command pipeline channel
  • puts – Write to a channel
  • read – Read from a channel
  • seek – Change the access position for an open channel
  • socket – Open a TCP network connection
  • tell – Return current access position for an open channel

interpreter manipulation commands

  • auto_execok – Provides list of arguments for shell builtin
  • auto_import – Check if commands exist in autoloaded library
  • auto_load – Load definition for Tcl Command
  • auto_mkindex – Parses Tcl Scripts to generate tclIndex
  • auto_qualify Computes fully qualified names for a command
  • auto_reset – Destroys auto_execok and auto_load cache
  • history – Manipulate the history list
  • info – Return information about the state of the Tcl interpreter
  • interp – Create and manipulate Tcl interpreters
  • load – Load machine code and initialize new commands.
  • package – Facilities for package loading and version control
  • pkg::create – Construct an appropriate package ifneeded command for a given package specification
  • pkg_mkIndex – Build an index for automatic loading of packages
  • Safe Base – A mechanism for creating and manipulating safe interpreters.
  • source – Evaluate a file or resource as a Tcl script
  • tcl_findLibrary – Search Standard Locations for script library

event-loop control commands

  • after – Execute a command after a time delay
  • vwait – Process events until a variable is written
  • update – Process pending events and idle callbacks

exception, error and debug commands

  • bgerror – Command invoked to process background errors
  • catch – Evaluate script and trap exceptional returns
  • memory – Control Tcl memory debugging capabilities.
  • time – Time the execution of a script
  • trace – Monitor variable accesses

TCL Generic Commands

  • clock – Obtain and manipulate time
  • Http – Client-side implementation of the HTTP/1.0 protocol.
  • msgcat – Multilingual Interface Support

TCL Standard Library Variables

  • $auto_execs
  • $auto_index
  • $auto_noexec
  • $auto_noload
  • $auto_path
  • env(TCL_LIBRARY)
  • env(TCLLIBPATH)
  • tcl_nonwordchars
  • tcl_wordchars
  • unknown_pending
array anymore arrayName searchId
array donesearch arrayName searchId
array exists arrayName
array get arrayName ?pattern?
array names arrayName ?pattern?
array nextelement arrayName searchId
array set arrayName list
array size arrayName
array startsearch arrayName
array unset arrayName ?pattern?
array anymore arrayName searchId
array donesearch arrayName searchId
array exists arrayName
array get arrayName ?pattern?
array names arrayName ?pattern?
array nextelement arrayName searchId
array set arrayName list
array size arrayName
array startsearch arrayName
array unset arrayName ?pattern?

auto_execok cmd
auto_import pattern
auto_load cmd
auto_mkindex dir pattern pattern ...
auto_mkindex_old dir pattern pattern ...
auto_qualify command namespace
auto_reset

append varName ?value value value ...?

bgerror message

binary format formatString ?arg arg ...?
binary scan string formatString ?varName varName ...?

break

catch script ?varName?

cd ?dirName?

clock format clockValue ?-format string? ?-gmt boolean?
clock scan dateString ?-base clockVal? ?-gmt boolean?
clock seconds

close channelId

concat ?arg arg ...?

package require dde 1.1
dde ?-async? servername ?topic?
dde ?-async? execute service topic data
dde ?-async? poke service topic item data
dde ?-async? request service topic item
dde ?-async? services service topic
dde ?-async? eval topic cmd ?arg arg ...?

eof channelId

error message ?info? ?code?

eval arg ?arg ...?

fblocked channelId

fconfigure channelId
fconfigure channelId name
fconfigure channelId name value ?name value ...?
     -blocking boolean                -eofchar char
     -buffering newValue              -eofchar {inchar outChar}
     -buffersize newSize              -translation mode
     -encoding name                   -translation {inMode outMode}
                                          mode: auto, binary, cr, crlf, lf

      Serial Ports                     Sockets (read only)
     -mode baud,parity,data,stop      -error
     -pollinterval msec               -sockname
     -lasterror                       -peername

fcopy inchan outchan ?-size size? ?-command callback?

file atime name ?time?
file attributes name
file channels ?pattern?
file copy ?-force? ?- -? source target
file delete ?-force? ?- -? pathname ?pathname ... ?
file dirname name
file executable name
file exists name
file extension name
file isdirectory name
file isfile name
file join name ?name ...?
file lstat name varName
file mkdir dir ?dir ...?
file mtime name ?time?
file nativename name
file owned name
file pathtype name
file readable name
file readlink name
file rename ?-force? ?- -? source target
file rename ?-force? ?- -? source ?source ...? targetDir
file rootname name
file size name
file split name
file stat name varName
file tail name
file type name
file volume
file writable name

fileevent channelId readable ?script?
fileevent channelId writable ?script?

for start test next body

flush channelId

foreach varname list body
foreach varlist1 list1 ?varlist2 list2 ...? body

gets channelId ?varName?

glob ?options? pattern ?pattern ...?
      -directory directory     -join      -nocomplain      -path pathPrefix
          -types typeList      --

    ?           match any single character
    *           match ny sequence
    [chars]     match any single character in chars
    \x          match character
    {a,b,...}   match any string in list

global varname ?varname ...?

history
history add command ?exec?
history change newValue ?event?
history clear
history event ?event?
history info ?count?
history keep ?count?
history nextid
history redo ?event?

::http::config ?options?
         -accept mimetypes     -proxyhost hostname          -proxyport number
      -useragent string      -proxyfilter command

::http::geturl url ?options?
      -blocksize size            -command callback              -query query
        -headers keyvaluelist    -handler callback     -queryblocksize size
        -channel name           -progress callback       -querychannel channelID
           -type mime-type       -timeout milliseconds  -queryprogress callback
   -    validate boolean

::http::formatQuery key value ?key value ...?
::http::reset token ?why?
::http::wait token
::http::data token
::http::error token
::http::status token
::http::code token
::http::ncode token
::http::size token
::http::cleanup token
::http::register proto port command
::http::unregister proto

if expr1 ?then? body1 elseif expr2 ?then?body2 elseif ... ?else? ?bodyN?

incr varName ?increment?

info args procname
info body procname
info cmdcount
info commands ?pattern?
info complete command
info default procname arg varname
info exists varName
info globals ?pattern?
info hostname
info level ?number?
info library
info loaded ?interp?
info locals ?pattern?
info nameofexecutable
info patchlevel
info procs ?pattern?
info script
info sharedlibextension
info tclversion
info vars ?pattern?

interp alias srcPath srcCmd
interp alias srcPath srcCmd {}
interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...?
interp aliases ?path?
interp create ?-safe? ?- -? ?path?
interp delete ?path ...?
interp eval path arg ?arg ...?
interp exists path
interp expose path hiddenName ?exposedCmdName?
interp hide path exposedCmdName ?hiddenCmdName?
interp hidden path
interp invokehidden path ?-global? hiddenCmdName ?arg ...?
interp issafe ?path?
interp marktrusted path
interp share srcPath channelId destPath
interp slaves ?path?
interp target path alias
interp transfer srcPath channelId destPath

::safe::interpCreate ?slave? ?switches? 
::safe::interpInit slave ?switches? 
::safe::interpConfigure slave ?switches? 
      -accessPath directoryList    -statics boolean      -noStatics
      -nested boolean              -deleteHook script    -nestedLoadOk

::safe::interpDelete slave
::safe::interpFindInAccessPath slave directory
::safe::interpAddToAccessPath slave directory
::safe::setLogCmd ?cmd arg...?

slave aliases
slave alias srcCmd
slave alias srcCmd {}
slave alias srcCmd targetCmd ?arg ..?
slave eval arg ?arg ..?
slave expose hiddenName ?exposedCmdName?
slave hide exposedCmdName ?hiddenCmdName?
slave hidden
slave invokehidden ?-global hiddenName ?arg ..?
slave issafe
slave marktrusted

join list ?joinString?

lappend varName ?value value value ...?

lindex list index

linsert list index element ?element element ...?

list ?arg arg ...?

llength list

load fileName
load fileName packageName
load fileName packageName interp

lrange list first last

lreplace list first last ?element element ...?

lsearch ?mode? list pattern

lsort ?switches? list
      -ascii        -dictionary   -integer      -real    -command command
      -increasing   -decreasing   -index index  -unique

memory info
memory trace [on|off]
memory validate [on|off]
memory trace_on_at_malloc count
memory break_on_malloc count
memory display file

::msgcat::mc src-string ?arg arg ...?
::msgcat::mclocale ?newLocale?
::msgcat::mcpreferences
::msgcat::mcload dirname
::msgcat::mcset locale src-string ?translate-string?
::msgcat::mcunknown locale src-string

namespace children ?namespace? ?pattern?
namespace code script
namespace current
namespace delete ?namespace namespace ...?
namespace eval namespace arg ?arg ...?
namespace export ?-clear? ?pattern pattern ...?
namespace forget ?pattern pattern ...?
namespace import ?-force? ?pattern pattern ...?
namespace inscope namespace arg ?arg ...?
namespace origin command
namespace parent ?namespace?
namespace qualifiers string
namespace tail string
namespace which ?-command? ?-variable? name

open fileName
open fileName access
open fileName access permissions

  r         read file, file must exist (default)
  r+        read/write, file must exist
  w         write, create if needed, overwrite
  w+        read/write, create if needed, overwrite
  a         write, create if needed, append
  a+        read/write, create if needed, append

  RDONLY    read only
  WRONLY    write only
  RDWR      read and write
  APPEND    set file pointer to end of file
  CREAT     create if needed
  EXCL      return error if file exist
  NOCTTY    if file is tty, prevent file from 
            becoming controling tty
  NONBLOCK  prevent process from blocking
  TRUNC     if file exists, truncate to 0 length

package forget ?package package ...?
package ifneeded package version ?script?
package names
package present ?-exact? package ?version?
package provide package ?version?
package require ?-exact? package ?version?
package unknown ?command?
package vcompare version1 version2
package versions package
package vsatisfies version1 version2
::pkg::create -name packageName -version packageVersion 
              ?-load filespec? ... ?-source filespec? ...

pkg_mkIndex ?switches? dir ?pattern pattern ...?
   -lazy    -load pkgPat    -verbose    --

parray arrayName

proc name args body

puts ?-nonewline? ?channelId? string

pwd

read ?-nonewline? channelId
read channelId numChars

regexp ?switches? exp string ?matchVar? ?subMatchVar subMatchVar ...?
  -all        -line          -nocase     
  -indices    -linestop      -expanded   
  -inline     -lineanchor    -start index

regsub ?switches? exp string subSpec varName
  -all        -line          -nocase
              -linestop      -expanded
              -lineanchor    -start index

rename oldName newName

return ?-code code? ?-errorinfo info? ?-errorcode code? ?string?
     code: ok, error, return, break, continue, value

scan string format ?varName varName ...?

        conversion specifier format: [%][#$][*][w][f]
     %: seq start   #$: arg index of variable       f: field-type
     *: discard      w: max-field-width

        field types:
     d: dec-int      o: oct-int       x: hex-int    u: uint     i: int
     e: float***     f: float***      g: float***               n: count   
   […]: chars     [^…]: NOT chars     s: non-space   ***same-function

seek channelId offset ?origin?
   origin: start, current, end (negative offset)

set varName ?value?

socket ?switches? host port
socket server command ?switches? port
          -myaddr addr    -myport port    -async    -myaddr addr

source fileName
source -rsrc resourceName ?fileName?
source -rsrcid resourceId ?fileName?

switch ?switches? string pattern body ?pattern body ...?
switch ?switches? string {pattern body ?pattern body ...?}
          -exact    -glob    -regexp    --

subst ?-nobackslashes? ?-nocommands? ?-novariables? string

tcl_findLibrary basename version patch initScript enVarName varName
tcl_endOfWord str start
tcl_startOfNextWord str start
tcl_startOfPreviousWord str start
tcl_wordBreakAfter str start
tcl_wordBreakBefore str start

tell channelId

time script ?count?

trace variable name ops command
         ops: r w u

trace vdelete name ops command
trace vinfo name

unknown cmdName ?arg arg ...?

unset name ?name name ...?

update ?idletasks?

uplevel ?level? arg ?arg ...?

variable ?name value...? name ?value?

vwait varName

while test body

Regular Expression Syntax

Standard Sequences

  * 0+ greedy matches         {#} # greedy matches            *? 0+ non-greedy
  + 1+ greedy matches        {#,} #+ greedy matches           +? 1+ non-greedy
  ? 0-1 greedy matches      {#,#} #-# greedy matches        {…}? non-greedy

Atom Definition

(…) captured ref            (?:…) non-captured ref        (?:=…) lookahead
 () empty ref                (?:) non-cap empty ref        (?!…) neg lookahead
  . any char                  […] any char in bracket  
  ^ beginning of line           $ end of line

Escape Sequences

\a  alert (bell) char                      \t          horizontal tab char
\b  backspace char                         \u####      hex 16-bit unicode char
\B  synonym for \                          \v########  hex 32-bit unicode char
\c? matches bitwise-and of char            \x#…        hex char of any length
\e  ESC, 27, 033, x1B                      \0          NULL char
\f  formfeed                               \#…         octal character (0??)
\n  newline                                \r          carriage return

AREs - Character Class Shorthand

\d  [[:digit:]]             \s  [[:space:]]             \w [[:alnum:]_]
\D  [^[:digit:]]            \S  [^[:space:]]            \W [^[:alnum:]_]

\A  start of string         \m  start of word           \y  start/end of word
\Z  end of string           \M  end of word             \Y  within word

\#  # != 0, backref
Advertisements