SYNOPSIS
cc <source> -ljim
or
jimsh [<scriptfile>|-]
jimsh -e '<immediate-script>'
jimsh --version
jimsh --help
INTRODUCTION
Jim Tcl is a small footprint reimplementation of the Tcl scripting language. The core language engine is compatible with Tcl 8.5+, while implementing a significant subset of the Tcl 8.6 command set, plus additional features available only in Jim Tcl.
Some notable differences with Tcl 8.5/8.6/8.7 are:
-
Object-based I/O (aio), but with a Tcl-compatibility layer
-
I/O: Support for sockets and pipes including udp, unix domain sockets and IPv6
-
Integers are 64bit
-
Support for references (
ref
/getref
/setref
) and garbage collection -
Builtin dictionary type (
dict
) with some limitations compared to Tcl 8.6 -
env
command to access environment variables -
Operating system features:
os.fork
,os.uptime
,wait
,signal
,alarm
,sleep
-
Much better error reporting.
info
stacktrace
as a replacement for $errorInfo, $errorCode -
Support for "static" variables in procedures
-
Threads and coroutines are not supported
-
Command and variable traces are not supported
-
Built-in command line editing
-
Expression shorthand syntax:
$(…)
-
Modular build allows many features to be omitted or built as dynamic, loadable modules
-
Highly suitable for use in an embedded environment
-
Support for UDP, IPv6, Unix-Domain sockets in addition to TCP sockets
RECENT CHANGES
Changes between 0.81 and 0.82
-
try
now supports trap to match on errorcode -
TIP 603,
aio
stat
is now supported to stat a file handle -
Add support for
socket
-async
-
The handles created by
socket
pty
now make the replica name available via filename -
info
frame
now returns a (largely) Tcl-compatible dictionary, and supports info frame 0 -
vwait
-signal
is now supported -
./configure now defaults to --full
-
New
timerate
command as an improvement overtime
, somewhat compatible with TIP 527 -
Add
ensemble
command and support fornamespace
ensemble
(as an optional extension)
Changes between 0.80 and 0.81
-
TIP 582, comments allowed in expressions
-
Many commands now accept "safe" integer expressions rather than simple integers:
loop
,range
,incr
,string
repeat
,lrepeat
,pack
,unpack
,rand
-
String and list indexes now accept integer expressions (STRING AND LIST INDEX SPECIFICATIONS)
-
loop
can now omit the start value -
Add the
xtrace
command for execution trace support -
Add
history
keep
-
Add support for
lsearch
-index
andlsearch
-stride
, the latter per TIP 351 -
lsort
-index
now supports multiple indices -
Add support for
lsort
-stride
-
open
now supports POSIX-style access arguments -
TIP 526,
expr
now only allows a single argument (unless --compat is enabled)
Changes between 0.79 and 0.80
-
regsub
now fully supports\A
-
Add
socket
pty
to create a pseudo-tty pair -
Null characters (\x00) are now supported in variable and proc names
-
dictionaries and arrays now preserve insertion order, matching Tcl and the documentation
-
Add
dict
getwithdefault
(and the aliasdict
getdef
) per TIP 342 -
Add string comparison operators (lt, gt, le, ge) per TIP 461
-
Implement 0d radix prefix for decimal per TIP 472
Changes between 0.78 and 0.79
-
Add
file
mtimeus
for high resolution file timestamps -
aio
now supports datagram Unix-Domain sockets -
Add support for
aio
lock -wait
-
Add
signal
block
to prevent delivery of signals -
Add support for
file
split
-
Add support for
json::encode
andjson::decode
-
aio
tty
now allows settingecho
without fullraw
mode
Changes between 0.77 and 0.78
-
Add serial/tty support with
aio
tty
-
Add support for jimsh -
-
Add hidden -commands option to many commands
-
Add scriptable autocompletion support in interactive mode with
tcl::autocomplete
-
Add
aio
sockopt
-
Add scriptable autocompletion support with
history
completion
-
Add support for
tree
delete
-
Add support for
defer
and $jim::defer -
Renamed
os.wait
towait
, now more Tcl-compatible and compatible withexec
... &
-
Closing a pipe open with
open
|...
now returns Tcl-like status -
It is now possible to used
exec
redirection with a pipe opened withopen
|...
-
Interactive line editing now supports multiline mode if $::history::multiline is set
Changes between 0.76 and 0.77
Changes between 0.75 and 0.76
Changes between 0.74 and 0.75
-
file
copy
-force
handles source and target as the same file -
format
now supports%b
for binary conversion -
lsort
now supports-unique
and-real
-
Add support for half-close with
aio
close
?r|w?
-
Add
socket
pair
for a bidirectional pipe -
Add --random-hash to randomise hash tables for greater security
-
dict
now supports for, values, incr, append, lappend, update, info and replace -
file
stat
no longer requires the variable name -
Add support for
file
link
TCL INTRODUCTION
Tcl stands for tool command language and is pronounced tickle. It is actually two things: a language and a library.
First, Tcl is a simple textual language, intended primarily for issuing commands to interactive programs such as text editors, debuggers, illustrators, and shells. It has a simple syntax and is also programmable, so Tcl users can write command procedures to provide more powerful commands than those in the built-in set.
Second, Tcl is a library package that can be embedded in application programs. The Tcl library consists of a parser for the Tcl language, routines to implement the Tcl built-in commands, and procedures that allow each application to extend Tcl with additional commands specific to that application. The application program generates Tcl commands and passes them to the Tcl parser for execution. Commands may be generated by reading characters from an input source, or by associating command strings with elements of the application’s user interface, such as menu entries, buttons, or keystrokes.
When the Tcl library receives commands it parses them into component fields and executes built-in commands directly. For commands implemented by the application, Tcl calls back to the application to execute the commands. In many cases commands will invoke recursive invocations of the Tcl interpreter by passing in additional strings to execute (procedures, looping commands, and conditional commands all work in this way).
An application program gains three advantages by using Tcl for its command language. First, Tcl provides a standard syntax: once users know Tcl, they will be able to issue commands easily to any Tcl-based application. Second, Tcl provides programmability. All a Tcl application needs to do is to implement a few application-specific low-level commands. Tcl provides many utility commands plus a general programming interface for building up complex command procedures. By using Tcl, applications need not re-implement these features.
Third, Tcl can be used as a common language for communicating between applications. Inter-application communication is not built into the Tcl core described here, but various add-on libraries, such as the Tk toolkit, allow applications to issue commands to each other. This makes it possible for applications to work together in much more powerful ways than was previously possible.
Fourth, Jim Tcl includes a command processor, jimsh
, which can be
used to run standalone Tcl scripts, or to run Tcl commands interactively.
This manual page focuses primarily on the Tcl language. It describes the language syntax and the built-in commands that will be available in any application based on Tcl. The individual library procedures are described in more detail in separate manual pages, one per procedure.
JIMSH COMMAND INTERPRETER
A simple, but powerful command processor, jimsh
, is part of Jim Tcl.
It may be invoked in interactive mode as:
jimsh
or to process the Tcl script in a file with:
jimsh filename
or to process the Tcl script from standard input:
jimsh -
It may also be invoked to execute an immediate script with:
jimsh -e "script"
Interactive Mode
Interactive mode reads Tcl commands from standard input, evaluates those commands and prints the results.
$ jimsh
Welcome to Jim version 0.73, Copyright (c) 2005-8 Salvatore Sanfilippo
. info version
0.73
. lsort [info commands p*]
package parray pid popen proc puts pwd
. foreach i {a b c} {
{> puts $i
{> }
a
b
c
. bad
invalid command name "bad"
[error] . exit
$
If jimsh
is configured with line editing (it is by default) and a VT-100-compatible
terminal is detected, Emacs-style line editing commands are available, including:
arrow keys, ^W
to erase a word, ^U
to erase the line, ^R
for reverse incremental search
in history. Additionally, the h
command may be used to display the command history.
Command line history is automatically saved and loaded from ~/.jim_history
In interactive mode, jimsh
automatically runs the script ~/.jimrc
at startup
if it exists.
INTERPRETERS
The central data structure in Tcl is an interpreter (C type Jim_Interp). An interpreter consists of a set of command bindings, a set of variable values, and a few other miscellaneous pieces of state. Each Tcl command is interpreted in the context of a particular interpreter.
Some Tcl-based applications will maintain multiple interpreters simultaneously, each associated with a different widget or portion of the application. Interpreters are relatively lightweight structures. They can be created and deleted quickly, so application programmers should feel free to use multiple interpreters if that simplifies the application.
DATA TYPES
Tcl supports only one type of data: strings. All commands, all arguments to commands, all command results, and all variable values are strings.
Where commands require numeric arguments or return numeric results, the arguments and results are passed as strings. Many commands expect their string arguments to have certain formats, but this interpretation is up to the individual commands. For example, arguments often contain Tcl command strings, which may get executed as part of the commands. The easiest way to understand the Tcl interpreter is to remember that everything is just an operation on a string. In many cases Tcl constructs will look similar to more structured constructs from other languages. However, the Tcl constructs are not structured at all; they are just strings of characters, and this gives them a different behaviour than the structures they may look like.
Although the exact interpretation of a Tcl string depends on who is doing the interpretation, there are three common forms that strings take: commands, expressions, and lists. The major sections below discuss these three forms in more detail.
BASIC COMMAND SYNTAX
The Tcl language has syntactic similarities to both the Unix shells and Lisp. However, the interpretation of commands is different in Tcl than in either of those other two systems. A Tcl command string consists of one or more commands separated by newline characters or semi-colons. Each command consists of a collection of fields separated by white space (spaces or tabs). The first field must be the name of a command, and the additional fields, if any, are arguments that will be passed to that command. For example, the command:
set a 22
has three fields: the first, set
, is the name of a Tcl command, and
the last two, a and 22, will be passed as arguments to
the set
command. The command name may refer either to a built-in
Tcl command, an application-specific command bound in with the library
procedure Jim_CreateCommand, or a command procedure defined with the
proc
built-in command.
Arguments are passed literally as text strings. Individual commands may
interpret those strings in any fashion they wish. The set
command,
for example, will treat its first argument as the name of a variable
and its second argument as a string value to assign to that variable.
For other commands arguments may be interpreted as integers, lists,
file names, or Tcl commands.
Command names should normally be typed completely (e.g. no abbreviations).
However, if the Tcl interpreter cannot locate a command it invokes a
special command named unknown
which attempts to find or create the
command.
For example, at many sites unknown
will search through library
directories for the desired command and create it as a Tcl procedure if
it is found. The unknown
command often provides automatic completion
of abbreviated commands, but usually only for commands that were typed
interactively.
It’s probably a bad idea to use abbreviations in command scripts and other forms that will be re-used over time: changes to the command set may cause abbreviations to become ambiguous, resulting in scripts that no longer work.
COMMENTS
If the first non-blank character in a command is #
, then everything
from the #
up through the next newline character is treated as
a comment and ignored. When comments are embedded inside nested
commands (e.g. fields enclosed in braces) they must have properly-matched
braces (this is necessary because when Tcl parses the top-level command
it doesn’t yet know that the nested field will be used as a command so
it cannot process the nested comment character as a comment).
GROUPING ARGUMENTS WITH DOUBLE-QUOTES
Normally each argument field ends at the next white space, but double-quotes may be used to create arguments with embedded space.
If an argument field begins with a double-quote, then the argument isn’t terminated by white space (including newlines) or a semi-colon (see below for information on semi-colons); instead it ends at the next double-quote character. The double-quotes are not included in the resulting argument. For example, the command
set a "This is a single argument"
will pass two arguments to set
: a and This is a single argument.
Within double-quotes, command substitutions, variable substitutions, and backslash substitutions still occur, as described below. If the first character of a command field is not a quote, then quotes receive no special interpretation in the parsing of that field.
GROUPING ARGUMENTS WITH BRACES
Curly braces may also be used for grouping arguments. They are similar to quotes except for two differences. First, they nest; this makes them easier to use for complicated arguments like nested Tcl command strings. Second, the substitutions described below for commands, variables, and backslashes do not occur in arguments enclosed in braces, so braces can be used to prevent substitutions where they are undesirable.
If an argument field begins with a left brace, then the argument ends at the matching right brace. Tcl will strip off the outermost layer of braces and pass the information between the braces to the command without any further modification. For example, in the command
set a {xyz a {b c d}}
the set
command will receive two arguments: a
and xyz a {b c d}.
When braces or quotes are in effect, the matching brace or quote need
not be on the same line as the starting quote or brace; in this case
the newline will be included in the argument field along with any other
characters up to the matching brace or quote. For example, the eval
command takes one argument, which is a command string; eval
invokes
the Tcl interpreter to execute the command string. The command
eval {
set a 22
set b 33
}
will assign the value 22 to a and 33 to b.
If the first character of a command field is not a left brace, then neither left nor right braces in the field will be treated specially (except as part of variable substitution; see below).
COMMAND SUBSTITUTION WITH BRACKETS
If an open bracket occurs in a field of a command, then command substitution occurs (except for fields enclosed in braces). All of the text up to the matching close bracket is treated as a Tcl command and executed immediately. Then the result of that command is substituted for the bracketed text. For example, consider the command
set a [set b]
When the set
command has only a single argument, it is the name of a
variable and set
returns the contents of that variable. In this case,
if variable b has the value foo, then the command above is equivalent
to the command
set a foo
Brackets can be used in more complex ways. For example, if the variable b has the value foo and the variable c has the value gorp, then the command
set a xyz[set b].[set c]
is equivalent to the command
set a xyzfoo.gorp
A bracketed command may contain multiple commands separated by newlines or semi-colons in the usual fashion. In this case the value of the last command is used for substitution. For example, the command
set a x[set b 22
expr $b+2]x
is equivalent to the command
set a x24x
If a field is enclosed in braces then the brackets and the characters between them are not interpreted specially; they are passed through to the argument verbatim.
VARIABLE SUBSTITUTION WITH $
The dollar sign ($
) may be used as a special shorthand form for
substituting variable values. If $
appears in an argument that isn’t
enclosed in braces then variable substitution will occur. The characters
after the $
, up to the first character that isn’t a number, letter,
or underscore, are taken as a variable name and the string value of that
variable is substituted for the name.
For example, if variable foo has the value test, then the command
set a $foo.c
is equivalent to the command
set a test.c
There are two special forms for variable substitution. If the next character after the name of the variable is an open parenthesis, then the variable is assumed to be an array name, and all of the characters between the open parenthesis and the next close parenthesis are taken as an index into the array. Command substitutions and variable substitutions are performed on the information between the parentheses before it is used as an index.
For example, if the variable x is an array with one element named first and value 87 and another element named 14 and value more, then the command
set a xyz$x(first)zyx
is equivalent to the command
set a xyz87zyx
If the variable index has the value 14, then the command
set a xyz$x($index)zyx
is equivalent to the command
set a xyzmorezyx
For more information on arrays, see VARIABLES - SCALARS AND ARRAYS below.
The second special form for variables occurs when the dollar sign is followed by an open curly brace. In this case the variable name consists of all the characters up to the next curly brace.
Array references are not possible in this form: the name between braces is assumed to refer to a scalar variable. For example, if variable foo has the value test, then the command
set a abc${foo}bar
is equivalent to the command
set a abctestbar
Variable substitution does not occur in arguments that are enclosed in braces: the dollar sign and variable name are passed through to the argument verbatim.
The dollar sign abbreviation is simply a shorthand form. $a
is
completely equivalent to [set a]
; it is provided as a convenience
to reduce typing.
SEPARATING COMMANDS WITH SEMI-COLONS
Normally, each command occupies one line (the command is terminated by a
newline character). However, semi-colon (;
) is treated as a command
separator character; multiple commands may be placed on one line by
separating them with a semi-colon. Semi-colons are not treated as
command separators if they appear within curly braces or double-quotes.
BACKSLASH SUBSTITUTION
Backslashes may be used to insert non-printing characters into command fields and also to insert special characters like braces and brackets into fields without them being interpreted specially as described above.
The backslash sequences understood by the Tcl interpreter are listed below. In each case, the backslash sequence is replaced by the given character:
-
\b
-
Backspace (0x8)
-
\f
-
Form feed (0xc)
-
\n
-
Newline (0xa)
-
\r
-
Carriage-return (0xd).
-
\t
-
Tab (0x9).
-
\v
-
Vertical tab (0xb).
-
\{
-
Left brace ({).
-
\}
-
Right brace (}).
-
\[
-
Open bracket ([).
-
\]
-
Close bracket (]).
-
\$
-
Dollar sign ($).
-
\<space>
-
Space ( ): doesn’t terminate argument.
-
\;
-
Semi-colon: doesn’t terminate command.
-
\"
-
Double-quote.
-
\<newline>
-
Nothing: this joins two lines together into a single line. This backslash feature is unique in that it will be applied even when the sequence occurs within braces.
-
\\
-
Backslash (\).
-
\ddd
-
The digits
ddd
(one, two, or three of them) give the octal value of the character. Note that Jim supports null characters in strings. -
\unnnn
-
\u{nnn}
-
\Unnnnnnnn
-
The UTF-8 encoding of the unicode codepoint represented by the hex digits,
nnnn
, is inserted. The u form allows for one to four hex digits. The U form allows for one to eight hex digits. The u{nnn} form allows for one to eight hex digits, but makes it easier to insert characters UTF-8 characters which are followed by a hex digit.
For example, in the command
set a {x\[\ yz\141
the second argument to set
will be {x[ yza
.
If a backslash is followed by something other than one of the options described above, then the backslash is transmitted to the argument field without any special processing, and the Tcl scanner continues normal processing with the next character. For example, in the command
set \*a \\{foo
The first argument to set
will be \*a
and the second
argument will be {foo
.
If an argument is enclosed in braces, then backslash sequences inside the argument are parsed but no substitution occurs (except for backslash-newline): the backslash sequence is passed through to the argument as is, without making any special interpretation of the characters in the backslash sequence. In particular, backslashed braces are not counted in locating the matching right brace that terminates the argument. For example, in the command
set a {{abc}
the second argument to set
will be {abc
.
This backslash mechanism is not sufficient to generate absolutely
any argument structure; it only covers the
most common cases. To produce particularly complicated arguments
it is probably easiest to use the format
command along with
command substitution.
STRING AND LIST INDEX SPECIFICATIONS
Many string and list commands take one or more index parameters which specify a position in the string relative to the start or end of the string/list.
The index may be one of the following forms:
-
integer
-
A simple integer, where
0
refers to the first element of the string or list. -
integerexpression
-
Any "safe" expression that evaluates to an integer. A "safe" expression does not perform variable or command subsitution, but is otherwise like a normal expression (see EXPRESSIONS).
-
For example
1+2*3
is valid integer expression, but{$x*2-1}
is not. But note that it is possible to use an unbraced expression to allow the Tcl interpreter to expand variables and commands before being parsed as an integer expression. -
e.g.
string repeat a $x*2-1
-
end
-
The last element of the string or list.
-
end-integer
-
end-integerexpression
-
end+integerexpression
-
The nth-from-last element of the string or list. Again, a "safe" integer expression may be used in place of a simple integer.
end-3
orend-3+2*$n
. Normally it only makes sense to use theend-
form, but if the integer expression is negative, theend
+ form may be used.
COMMAND SUMMARY
-
A command is just a string.
-
Within a string commands are separated by newlines or semi-colons (unless the newline or semi-colon is within braces or brackets or is backslashed).
-
A command consists of fields. The first field is the name of the command. The other fields are strings that are passed to that command as arguments.
-
Fields are normally separated by white space.
-
Double-quotes allow white space and semi-colons to appear within a single argument. Command substitution, variable substitution, and backslash substitution still occur inside quotes.
-
Braces defer interpretation of special characters. If a field begins with a left brace, then it consists of everything between the left brace and the matching right brace. The braces themselves are not included in the argument. No further processing is done on the information between the braces except that backslash-newline sequences are eliminated.
-
If a field doesn’t begin with a brace then backslash, variable, and command substitution are done on the field. Only a single level of processing is done: the results of one substitution are not scanned again for further substitutions or any other special treatment. Substitution can occur on any field of a command, including the command name as well as the arguments.
-
If the first non-blank character of a command is a
#
, everything from the#
up through the next newline is treated as a comment and ignored.
EXPRESSIONS
The second major interpretation applied to strings in Tcl is
as expressions. Several commands, such as expr
, for
,
and if
, treat one or more of their arguments as expressions
and call the Tcl expression processors (Jim_ExprLong,
Jim_ExprBoolean, etc.) to evaluate them.
The operators permitted in Tcl expressions are a subset of the operators permitted in C expressions, and they have the same meaning and precedence as the corresponding C operators. Expressions almost always yield numeric results (integer or floating-point values). For example, the expression
8.2 + 6
evaluates to 14.2.
Tcl expressions differ from C expressions in the way that operands are specified, and in that Tcl expressions support non-numeric operands and string comparisons.
A Tcl expression consists of a combination of operands, operators, and parentheses.
White space may be used between the operands and operators and parentheses; it is ignored by the expression processor. Where possible, operands are interpreted as integer values.
Comments are allowed in expressions, beginning with the # character and continuing until the end of line or end of expression.
Integer values are interpreted as decimal, binary, octal or hexadecimal if prepended with 0d, 0b, 0o or 0x respectively. Otherwise they are interpreted as decimal by default. (Jim Tcl does not interpret numbers with leading zeros as octal.)
If an operand does not have one of the integer formats given above, then it is treated as a floating-point number if that is possible. Floating-point numbers may be specified in any of the ways accepted by an ANSI-compliant C compiler (except that the f, F, l, and L suffixes will not be permitted in most installations). For example, all of the following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16.
If no numeric interpretation is possible, then an operand is left as a string (and only a limited set of operators may be applied to it).
String constants representing boolean constants
(0
, 1
, false
, off
, no
, true
, on
, yes
)
are also recognized and can be used in logical operations.
-
Operands may be specified in any of the following ways:
-
As a numeric value, either integer or floating-point.
-
As one of valid boolean constants
-
As a Tcl variable, using standard $ notation. The variable’s value will be used as the operand.
-
As a string enclosed in double-quotes. The expression parser will perform backslash, variable, and command substitutions on the information between the quotes, and use the resulting value as the operand
-
As a string enclosed in braces. The characters between the open brace and matching close brace will be used as the operand without any substitutions.
-
As a Tcl command enclosed in brackets. The command will be executed and its result will be used as the operand.
Where substitutions occur above (e.g. inside quoted strings), they are performed by the expression processor. However, an additional layer of substitution may already have been performed by the command parser before the expression processor was called.
As discussed below, it is usually best to enclose expressions in braces to prevent the command parser from performing substitutions on the contents.
For some examples of simple expressions, suppose the variable a has the value 3 and the variable b has the value 6. Then the expression on the left side of each of the lines below will evaluate to the value on the right side of the line:
$a + 3.1 6.1
2 + "$a.$b" 5.6
4*[llength "6 2"] 8
{word one} < "word $a" 0
The valid operators are listed below, grouped in decreasing order of precedence:
-
int() double() round() abs(), rand(), srand()
-
Unary functions (except rand() which takes no arguments)
-
int()
converts the numeric argument to an integer by truncating down. -
double()
converts the numeric argument to floating point. -
round()
converts the numeric argument to the closest integer value. -
abs()
takes the absolute value of the numeric argument. -
rand()
returns a pseudo-random floating-point value in the range (0,1). -
srand()
takes an integer argument to (re)seed the random number generator. Returns the first random number from that seed.
-
-
sin() cos() tan() asin() acos() atan() sinh() cosh() tanh() ceil() floor() exp() log() log10() sqrt()
-
Unary math functions. If Jim is compiled with math support, these functions are available.
-
- + ~ !
-
Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operands may be applied to string operands, and bit-wise NOT may be applied only to integers.
-
** pow(x,y)
-
Power. e.g. xy. If Jim is compiled with math support, supports doubles and integers. Otherwise supports integers only. (Note that the math-function form has the same highest precedence)
-
* / %
-
Multiply, divide, remainder. None of these operands may be applied to string operands, and remainder may be applied only to integers.
-
+ -
-
Add and subtract. Valid for any numeric operands.
-
<< >> <<< >>>
-
Left and right shift, left and right rotate. Valid for integer operands only.
-
< > <= >=
-
Boolean less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These operators may be applied to strings as well as numeric operands, in which case string comparison is used.
-
lt gt le ge
-
Boolean less, greater, less than or equal, and greater than or equal. Each operator produces 1 if the condition is true, 0 otherwise. These operators differ from the above in that they use string comparison for all operands, including numeric.
-
== !=
-
Boolean equal and not equal. Each operator produces a zero/one result. Valid for all operand types. Note that values will be converted to integers if possible, then floating point types, and finally strings will be compared. It is recommended that eq and ne should be used for string comparison.
-
eq ne
-
String equal and not equal. Uses the string value directly without attempting to convert to a number first.
-
in ni
-
String in list and not in list. For in, result is 1 if the left operand (as a string) is contained in the right operand (as a list), or 0 otherwise. The result for
{$a ni $list}
is equivalent to{!($a in $list)}
. -
&
-
Bit-wise AND. Valid for integer operands only.
-
|
-
Bit-wise OR. Valid for integer operands only.
-
^
-
Bit-wise exclusive OR. Valid for integer operands only.
-
&&
-
Logical AND. Produces a 1 result if both operands are non-zero, 0 otherwise. Valid for numeric operands only (integers or floating-point).
-
||
-
Logical OR. Produces a 0 result if both operands are zero, 1 otherwise. Valid for numeric operands only (integers or floating-point).
-
x ? y : z
-
If-then-else, as in C. If
x
evaluates to non-zero, then the result is the value ofy
. Otherwise the result is the value ofz
. Thex
operand must have a numeric value, whiley
andz
can be of any type.
See the C manual for more details on the results produced by each operator. All of the binary operators group left-to-right within the same precedence level. For example, the expression
4*2 < 7
evaluates to 0.
The &&
, ||
, and ?:
operators have lazy evaluation, just as
in C, which means that operands are not evaluated if they are not
needed to determine the outcome. For example, in
$v ? [a] : [b]
only one of [a]
or [b]
will actually be evaluated,
depending on the value of $v
.
All internal computations involving integers are done with the C type long long if available, or long otherwise, and all internal computations involving floating-point are done with the C type double.
When converting a string to floating-point, exponent overflow is detected and results in a Tcl error. For conversion to integer from string, detection of overflow depends on the behaviour of some routines in the local C library, so it should be regarded as unreliable. In any case, overflow and underflow are generally not detected reliably for intermediate results.
Conversion among internal representations for integer, floating-point, string operands is done automatically as needed. For arithmetic computations, integers are used until some floating-point number is introduced, after which floating-point is used. For example,
5 / 4
yields the result 1, while
5 / 4.0
5 / ( [string length "abcd"] + 0.0 )
both yield the result 1.25.
String values may be used as operands of the comparison operators, although the expression evaluator tries to do comparisons as integer or floating-point when it can. If one of the operands of a comparison is a string and the other has a numeric value, the numeric operand is converted back to a string using the C sprintf format specifier %d for integers and %g for floating-point values. For example, the expressions
"0x03" > "2"
"0y" < "0x12"
both evaluate to 1. The first comparison is done using integer comparison, and the second is done using string comparison after the second operand is converted to the string 18.
In general it is safest to enclose an expression in braces when entering it in a command: otherwise, if the expression contains any white space then the Tcl interpreter will split it among several arguments. For example, the command
expr $a + $b
results in three arguments being passed to expr
: $a
,
+, and $b
. In addition, if the expression isn’t in braces
then the Tcl interpreter will perform variable and command substitution
immediately (it will happen in the command parser rather than in
the expression parser). In many cases the expression is being
passed to a command that will evaluate the expression later (or
even many times if, for example, the expression is to be used to
decide when to exit a loop). Usually the desired goal is to re-do
the variable or command substitutions each time the expression is
evaluated, rather than once and for all at the beginning. For example,
the command
for {set i 1} $i<=10 {incr i} {...} ** WRONG **
is probably intended to iterate over all values of i
from 1 to 10.
After each iteration of the body of the loop, for
will pass
its second argument to the expression evaluator to see whether or not
to continue processing. Unfortunately, in this case the value of i
in the second argument will be substituted once and for all when the
for
command is parsed. If i
was 0 before the for
command was invoked then the second argument of for
will be 0<=10
which will always evaluate to 1, even though i
eventually
becomes greater than 10. In the above case the loop will never
terminate. Instead, the expression should be placed in braces:
for {set i 1} {$i<=10} {incr i} {...} ** RIGHT **
This causes the substitution of i to be delayed; it will be re-done each time the expression is evaluated, which is the desired result.
LISTS
The third major way that strings are interpreted in Tcl is as lists. A list is just a string with a list-like structure consisting of fields separated by white space. For example, the string
Al Sue Anne John
is a list with four elements or fields. Lists have the same basic structure as command strings, except that a newline character in a list is treated as a field separator just like space or tab. Conventions for braces and quotes and backslashes are the same for lists as for commands. For example, the string
a b\ c {d e {f g h}}
is a list with three elements: a
, b c
, and d e {f g h}
.
Whenever an element is extracted from a list, the same rules about braces and quotes and backslashes are applied as for commands. Thus in the example above when the third element is extracted from the list, the result is
d e {f g h}
(when the field was extracted, all that happened was to strip off the outermost layer of braces). Command substitution and variable substitution are never made on a list (at least, not by the list-processing commands; the list can always be passed to the Tcl interpreter for evaluation).
LIST EXPANSION
A new addition to Tcl 8.5 is the ability to expand a list into separate arguments. Support for this feature is also available in Jim.
Consider the following attempt to exec a list:
set cmd {ls -l}
exec $cmd
This will attempt to exec a command named "ls -l", which will clearly not
work. Typically eval and concat are required to solve this problem, however
it can be solved much more easily with \{*}
.
exec {*}$cmd
This will expand the following argument into individual elements and then evaluate the resulting command.
Note that the official Tcl syntax is \{*}
, however {expand}
is retained
for backward compatibility with experimental versions of this feature.
REGULAR EXPRESSIONS
Jim Tcl provides two commands that support string matching using regular
expressions, regexp
and regsub
, as well as switch
-regexp
and
lsearch
-regexp
.
Regular expressions may be implemented one of two ways. Either using the system’s C library POSIX regular expression support, or using the built-in regular expression engine. The differences between these are described below.
NOTE Tcl 7.x and 8.x use perl-style Advanced Regular Expressions (ARE
).
POSIX Regular Expressions
If the system supports POSIX regular expressions, and UTF-8 support is not enabled,
this support will be used by default. The type of regular expressions supported are
Extended Regular Expressions (ERE
) rather than Basic Regular Expressions (BRE
).
See REG_EXTENDED in the documentation.
Using the system-supported POSIX regular expressions will typically
make for the smallest code size, but some features such as UTF-8
and \w
, \d
, \s
are not supported, and null characters
in strings are not supported.
See regex(3) and regex(7) for full details.
Jim built-in Regular Expressions
The Jim built-in regular expression engine may be selected with ./configure --with-jim-regexp
or it will be selected automatically if UTF-8 support is enabled.
This engine supports UTF-8 as well as some ARE
features. The differences with both Tcl 7.x/8.x
and POSIX are highlighted below.
-
UTF-8 strings and patterns are both supported
-
All Tcl character classes are supported (e.g.
[:alnum:]
,[:digit:]
,[:space:]
), but… -
Character classes apply to ASCII characters only
-
Supported shorthand character classes:
\w
=[:alnum:]
,\W
=^[:alnum:]
,\d
=[:digit:],
\D
=^[:digit:],
\s
=[:space:]
, +\S
=^[:space:]
-
Supported constraint escapes:
\m
=\<
= start of word,\M
=\>
= end of word,\A
= start of string,\Z
= end of string -
Backslash escapes may be used within regular expressions, such as
\n
= newline,\uNNNN
= unicode -
Support for the
?
non-greedy quantifier. e.g.*?
-
Support for non-capturing parentheses
(?:…)
-
Jim Tcl considers that both patterns and strings end at a null character (
\x00
) -
Jim Tcl does not support back references. e.g.
\1
STRING MATCHING
A number of commands in Jim support C-shell style "glob matching", including
string
match
, switch
-glob
, array
names
and others. This form of string matching
works as follows:
A test occurs where a string
is matched against a pattern
. The match is considered
successful if the contents of string
and pattern
are identical except that the
following special sequences may appear in pattern
:
-
*
-
Matches any sequence of characters in
string
, including an empty string. -
?
-
Matches any single character in
string
. -
[chars]
-
Matches any character in the set given by
chars
. If a sequence of the formx-y
appears inchars
, then any character betweenx
andy
, inclusive, will match. -
\x
-
Matches the single character
x
. This provides a way of avoiding the special interpretation of the characters\*?[]
inpattern
.
COMMAND RESULTS
Each command produces two results: a code and a string. The code indicates whether the command completed successfully or not, and the string gives additional information. The valid codes are defined in jim.h, and are:
-
JIM_OK(0)
-
This is the normal return code, and indicates that the command completed successfully. The string gives the command’s return value.
-
JIM_ERR(1)
-
Indicates that an error occurred; the string gives a message describing the error.
-
JIM_RETURN(2)
-
Indicates that the
return
command has been invoked, and that the current procedure (or top-level command orsource
command) should return immediately. The string gives the return value for the procedure or command. -
JIM_BREAK(3)
-
Indicates that the
break
command has been invoked, so the innermost loop should abort immediately. The string should always be empty. -
JIM_CONTINUE(4)
-
Indicates that the
continue
command has been invoked, so the innermost loop should go on to the next iteration. The string should always be empty. -
JIM_SIGNAL(5)
-
Indicates that a signal was caught while executing a commands. The string contains the name of the signal caught. See the
signal
andcatch
commands. -
JIM_EXIT(6)
-
Indicates that the command called the
exit
command. The string contains the exit code.
Tcl programmers do not normally need to think about return codes,
since JIM_OK
is almost always returned. If anything else is returned
by a command, then the Tcl interpreter immediately stops processing
commands and returns to its caller. If there are several nested
invocations of the Tcl interpreter in progress, then each nested
command will usually return the error to its caller, until eventually
the error is reported to the top-level application code. The
application will then display the error message for the user.
In a few cases, some commands will handle certain error
conditions
themselves and not return them upwards. For example, the for
command checks for the JIM_BREAK
code; if it occurs, then for
stops executing the body of the loop and returns JIM_OK
to its
caller. The for
command also handles JIM_CONTINUE
codes and the
procedure interpreter handles JIM_RETURN
codes. The catch
command allows Tcl programs to catch errors and handle them without
aborting command interpretation any further.
The info
returncodes
command may be used to programmatically map between
return codes and names.
PROCEDURES
Tcl allows you to extend the command interface by defining procedures. A Tcl procedure can be invoked just like any other Tcl command (it has a name and it receives one or more arguments). The only difference is that its body isn’t a piece of C code linked into the program; it is a string containing one or more other Tcl commands.
The proc
command is used to create a new Tcl command procedure:
proc name arglist ?statics? body
The new command is named name
, and it replaces any existing command
there may have been by that name. Whenever the new command is
invoked, the contents of body
will be executed by the Tcl
interpreter.
arglist
specifies the formal arguments to the procedure.
It consists of a list, possibly empty, of the following
argument specifiers:
-
name
-
Required Argument - A simple argument name.
-
{name default}
-
Optional Argument - A two-element list consisting of the argument name, followed by the default value, which will be used if the corresponding argument is not supplied.
-
&name
-
Reference Argument - The caller is expected to pass the name of an existing variable. An implicit
is done to make the variable available in the proc scope.upvar
1 origname name -
args
-
Variable Argument - The special name
args
, which is assigned all remaining arguments (including none) as a list. The variable argument may only be specified once. Note that the syntax{args newname}
may be used to retain the special behaviour ofargs
with a different local name. In this case, the variable is namednewname
rather thanargs
.
When the command is invoked, a local variable will be created for each of the formal arguments to the procedure; its value will be the value of corresponding argument in the invoking command or the argument’s default value.
Arguments with default values need not be specified in a procedure invocation. However, there must be enough actual arguments for all required arguments, and there must not be any extra actual arguments (unless the Variable Argument is specified).
Actual arguments are assigned to formal arguments as in left-to-right order with the following precedence.
-
Required Arguments (including Reference Arguments)
-
Optional Arguments
-
Variable Argument
The following example illustrates precedence. Assume a procedure declaration:
proc p {{a A} args b {c C} d} {...}
This procedure requires at least two arguments, but can accept an unlimited number.
The following table shows how various numbers of arguments are assigned.
Values marked as -
are assigned the default value.
| Number of arguments | a | args | b | c | d |
|---|---|---|---|---|---|
2 |
- |
- |
1 |
- |
2 |
3 |
1 |
- |
2 |
- |
3 |
4 |
1 |
- |
2 |
3 |
4 |
5 |
1 |
2 |
3 |
4 |
5 |
6 |
1 |
2,3 |
4 |
5 |
6 |
When body
is being executed, variable names normally refer to local
variables, which are created automatically when referenced and deleted
when the procedure returns. One local variable is automatically created
for each of the procedure’s arguments. Global variables can be
accessed by invoking the global
command or via the ::
prefix.
New in Jim
In addition to procedure arguments, Jim procedures may declare static variables. These variables scoped to the procedure and initialised at procedure definition. Either from the static variable definition, or from the enclosing scope.
Consider the following example:
. set a 1
. proc a {} {a {b 2}} {
set c 1
puts "$a $b $c"
incr a
incr b
incr c
}
. a
1 2 1
. a
2 3 1
The static variable a
has no initialiser, so it is initialised from
the enclosing scope with the value 1. (Note that it is an error if there
is no variable with the same name in the enclosing scope). However b
has an initialiser, so it is initialised to 2.
Unlike a local variable, the value of a static variable is retained across invocations of the procedure.
See the proc
command for information on how to define procedures
and what happens when they are invoked. See also NAMESPACES.
VARIABLES - SCALARS AND ARRAYS
Tcl allows the definition of variables and the use of their values
either through $-style variable substitution, the set
command, or a few other mechanisms.
Variables need not be declared: a new variable will automatically be created each time a new variable name is used.
Tcl supports two types of variables: scalars and arrays. A scalar variable has a single value, whereas an array variable can have any number of elements, each with a name (called its index) and a value.
Array indexes may be arbitrary strings; they need not be numeric. Parentheses are used refer to array elements in Tcl commands. For example, the command
set x(first) 44
will modify the element of x whose index is first so that its new value is 44.
Two-dimensional arrays can be simulated in Tcl by using indexes that contain multiple concatenated values. For example, the commands
set a(2,3) 1
set a(3,6) 2
set the elements of a whose indexes are 2,3 and 3,6.
In general, array elements may be used anywhere in Tcl that scalar variables may be used.
If an array is defined with a particular name, then there may not be a scalar variable with the same name.
Similarly, if there is a scalar variable with a particular name then it is not possible to make array references to the variable.
To convert a scalar variable to an array or vice versa, remove
the existing variable with the unset
command.
The array
command provides several features for dealing
with arrays, such as querying the names of all the elements of
the array and converting between an array and a list.
Variables may be either global or local. If a variable
name is used when a procedure isn’t being executed, then it
automatically refers to a global variable. Variable names used
within a procedure normally refer to local variables associated with that
invocation of the procedure. Local variables are deleted whenever
a procedure exits. Either global
command may be used to request
that a name refer to a global variable for the duration of the current
procedure (this is somewhat analogous to extern in C), or the variable
may be explicitly scoped with the ::
prefix. For example
. set a 1
. set b 2
. proc p {} {
set c 3
global a
puts "$a $::b $c"
}
. p
will output:
1 2 3
ARRAYS AS LISTS IN JIM
Unlike Tcl, Jim can automatically convert between a list (with an even number of elements) and an array value. This is similar to the way Tcl can convert between a string and a list.
For example:
set a {1 one 2 two}
puts $a(2)
will output:
two
The reverse is also true where an array will be converted into a list.
set a(1) one; set a(2) two
puts $a
will output:
1 one 2 two
DICTIONARY VALUES
Tcl 8.5 introduced the dict command, and Jim Tcl has added a version of this command. Dictionaries provide efficient access to key-value pairs, just like arrays, but dictionaries are pure values. This means that you can pass them to a procedure just as a list or a string. Tcl dictionaries are therefore much more like Tcl lists, except that they represent a mapping from keys to values, rather than an ordered sequence.
You can nest dictionaries, so that the value for a particular key consists of another dictionary. That way you can elegantly build complicated data structures, such as hierarchical databases. You can also combine dictionaries with other Tcl data structures. For instance, you can build a list of dictionaries that themselves contain lists.
Dictionaries are values that contain an efficient, order-preserving mapping from arbitrary keys to arbitrary values. Each key in the dictionary maps to a single value. They have a textual format that is exactly that of any list with an even number of elements, with each mapping in the dictionary being represented as two items in the list. When a command takes a dictionary and produces a new dictionary based on it (either returning it or writing it back into the variable that the starting dictionary was read from) the new dictionary will have the same order of keys, modulo any deleted keys and with new keys added on to the end. When a string is interpreted as a dictionary and it would otherwise have duplicate keys, only the last value for a particular key is used; the others are ignored, meaning that, "apple banana" and "apple carrot apple banana" are equivalent dictionaries (with different string representations).
Note that in Jim, arrays are implemented as dictionaries. Thus automatic conversion between lists and dictionaries applies as it does for arrays.
. dict set a 1 one
1 one
. dict set a 2 two
1 one 2 two
. puts $a
1 one 2 two
. puts $a(2)
two
. dict set a 3 T three
1 one 2 two 3 {T three}
See the dict
command for more details.
NAMESPACES
Tcl added namespaces as a mechanism avoiding name clashes, especially in applications including a number of 3rd party components. While there is less need for namespaces in Jim Tcl (which does not strive to support large applications), it is convenient to provide a subset of the support for namespaces to easy porting code from Tcl.
Jim Tcl currently supports "light-weight" namespaces which should be adequate for most
purposes. This feature is currently experimental. See README.namespaces for more information
and the documentation of the namespace
command.
GARBAGE COLLECTION, REFERENCES, LAMBDA FUNCTION
Unlike Tcl, Jim has some sophisticated support for functional programming. These are described briefly below.
More information may be found at http://wiki.tcl.tk/13847
References
A reference can be thought of as holding a value with one level of indirection, where the value may be garbage collected when unreferenced. Consider the following example:
. set r [ref "One String" test]
<reference.<test___>.00000000000000000000>
. getref $r
One String
The operation ref
creates a references to the value specified by the
first argument. (The second argument is a "type" used for documentation purposes).
The operation getref
is the dereferencing operation which retrieves the value
stored in the reference.
. setref $r "New String"
New String
. getref $r
New String
The operation setref
replaces the value stored by the reference. If the old value
is no longer accessible by any reference, it will eventually be automatically be garbage
collected.
Garbage Collection
Normally, all values in Tcl are passed by value. As such values are copied and released automatically as necessary.
With the introduction of references, it is possible to create values whose lifetime transcend their scope. To support this, case, the Jim system will periodically identify and discard objects which are no longer accessible by any reference.
The collect
command may be used to force garbage collection. Consider a reference created
with a finalizer:
. proc f {ref value} { puts "Finaliser called for $ref,$value" }
. set r [ref "One String" test f]
<reference.<test___>.00000000000
. collect
0
. set r ""
. collect
Finaliser called for <reference.<test___>.00000000000,One String
1
Note that once the reference, r, was modified so that it no longer contained a reference to the value, the garbage collector discarded the value (after calling the finalizer).
The finalizer for a reference may be examined or changed with the finalize
command
. finalize $r
f
. finalize $r newf
newf
Lambda Function
Jim provides a garbage collected lambda
function. This is a procedure
which is able to create an anonymous procedure. Consider:
. set f [lambda {a} {{x 0}} { incr x $a }]
. $f 1
1
. $f 2
3
. set f ""
This create an anonymous procedure (with the name stored in f), with a static variable which is incremented by the supplied value and the result returned.
Once the procedure name is no longer accessible, it will automatically be deleted when the garbage collector runs.
The procedure may also be delete immediately by renaming it "". e.g.
. rename $f ""
UTF-8 AND UNICODE
If Jim is built with UTF-8 support enabled (configure --enable-utf),
then most string-related commands become UTF-8 aware. These include,
but are not limited to, string
match
, split
, glob
, scan
and
format
.
UTF-8 encoding has many advantages, but one of the complications is that
characters can take a variable number of bytes. Thus the addition of
string
bytelength
which returns the number of bytes in a string,
while string
length
returns the number of characters.
If UTF-8 support is not enabled, all commands treat bytes as characters
and string
bytelength
returns the same value as string
length
.
Note that even if UTF-8 support is not enabled, the \uNNNN
and related syntax
is still available to embed UTF-8 sequences.
Jim Tcl supports all currently defined unicode codepoints. That is 21 bits, up to +U+1FFFFF.
String Matching
Commands such as string
match
, lsearch
-glob
, array
names
and others use
STRING MATCHING rules. These commands support UTF-8. For example:
string match a\[\ua0-\ubf\]b "a\u00a3b"
format and scan
format %c
allows a unicode codepoint to be be encoded. For example, the following will return
a string with two bytes and one character. The same as \ub5
format %c 0xb5
format
respects widths as character widths, not byte widths. For example, the following will
return a string with three characters, not three bytes.
format %.3s \ub5\ub6\ub7\ub8
Similarly, scan … %c
allows a UTF-8 to be decoded to a unicode codepoint. The following will set
a
to 181 (0xb5) and b
to 65 (0x41).
scan \u00b5A %c%c a b
scan
%s
will also accept a character class, including unicode ranges.
String Classes
string
is
has not been extended to classify UTF-8 characters. Therefore, the following
will return 0, even though the string may be considered to be alphabetic.
string is alpha \ub5Test
This does not affect the string classes ascii, control, digit, double, integer or xdigit.
Case Mapping and Conversion
Jim provides a simplified unicode case mapping. This means that case conversion and comparison will not increase or decrease the number of characters in a string. (Although it may change the number of bytes).
Invalid UTF-8 Sequences
Some UTF-8 character sequences are invalid, such as those beginning with 0xff, those which represent character sequences longer than 3 bytes (greater than U+FFFF), and those which end prematurely, such as a lone 0xc2.
In these situations, the offending bytes are treated as single characters. For example, the following returns 2.
string bytelength \xff\xff
Regular Expressions
If UTF-8 support is enabled, the built-in regular expression engine will be selected which supports UTF-8 strings and patterns.
BUILT-IN COMMANDS
The Tcl library provides the following built-in commands, which will be available in any application using Tcl. In addition to these built-in commands, there may be additional commands defined by each application, plus commands defined as Tcl procedures.
In the command syntax descriptions below, words in boldface
are
literals that you type verbatim to Tcl.
Words in italics
are meta-symbols; they serve as names for any of
a range of values that you can type.
Optional arguments or groups of arguments are indicated by enclosing them
in ?question-marks?
.
Ellipses (...
) indicate that any number of additional
arguments or groups of arguments may appear, in the same format
as the preceding argument(s).
Command Index
alarm
alarm seconds
Delivers the SIGALRM
signal to the process after the given
number of seconds. If the platform supports ualarm(3) then
the argument may be a floating point value. Otherwise it must
be an integer.
Note that unless a signal handler for SIGALRM
has been installed
(see signal
), the process will exit on this signal.
alias
alias name args...
Creates a single word alias (command) for one or more words. For example,
the following creates an alias for the command info
exists
.
alias e info exists
if {[e var]} {
...
}
append
append varName value ?value value …?
Append all of the value
arguments to the current value
of variable varName
. If varName
doesn’t exist,
it is given a value equal to the concatenation of all the
value
arguments.
apply
apply lambdaExpr ?arg1 arg2 ...?
array
array option arrayName ?arg...?
This command performs one of several operations on the
variable given by arrayName
.
Note that in general, if the named array does not exist, the array
command behaves
as though the array exists but is empty.
The option
argument determines what action is carried out by the
command. The legal options
(which may be abbreviated) are:
-
array exists arrayName
-
Returns 1 if
arrayName
is an array variable, 0 if there is no variable by that name. -
array get arrayName ?pattern?
-
Returns a list containing pairs of elements. The first element in each pair is the name of an element in
arrayName
and the second element of each pair is the value of the array element. The order of the pairs is undefined. Ifpattern
is not specified, then all of the elements of the array are included in the result. Ifpattern
is specified, then only those elements whose names matchpattern
(using STRING MATCHING rules) are included. IfarrayName
isn’t the name of an array variable, or if the array contains no elements, then an empty list is returned. -
array names arrayName ?pattern?
-
Returns a list containing the names of all of the elements in the array that match
pattern
. Ifpattern
is omitted then the command returns all of the element names in the array. Ifpattern
is specified, then only those elements whose names matchpattern
(using STRING MATCHING rules) are included. If there are no (matching) elements in the array, or ifarrayName
isn’t the name of an array variable, then an empty string is returned. -
array set arrayName list
-
Sets the values of one or more elements in
arrayName
.list
must have a form like that returned by array get, consisting of an even number of elements. Each odd-numbered element in list is treated as an element name within arrayName, and the following element in list is used as a new value for that array element. If the variablearrayName
does not already exist and list is empty,arrayName
is created with an empty array value. -
array size arrayName
-
Returns the number of elements in the array. If
arrayName
isn’t the name of an array then 0 is returned. -
array unset arrayName ?pattern?
-
Unsets all of the elements in the array that match
pattern
(using STRING MATCHING rules). IfarrayName
isn’t the name of an array variable or there are no matching elements in the array, no error will be raised. Ifpattern
is omitted andarrayName
is an array variable, then the command unsets the entire array. The command always returns an empty string.
break
break
case
The obsolete case
command has been removed from Jim Tcl since v0.75.
Use switch
instead.
catch
catch ?-?no?code ...? ?--? command ?resultVarName? ?optionsVarName?
The catch
command may be used to prevent errors from aborting
command interpretation. catch
evaluates command
, and returns a
JIM_OK
code, regardless of any errors that might occur while
executing command
(with the possible exception of JIM_SIGNAL
-
see below).
The return value from catch
is a decimal string giving the code
returned by the Tcl interpreter after executing command
. This
will be 0 (JIM_OK
) if there were no errors in command
; otherwise
it will have a non-zero value corresponding to one of the exceptional
return codes (see jim.h for the definitions of code values, or the
info
returncodes
command).
If the resultVarName
argument is given, then it gives the name
of a variable; catch
will set the value of the variable to the
string returned from command
(either a result or an error message).
If the optionsVarName
argument is given, then it gives the name
of a variable; catch
will set the value of the variable to a
dictionary. For any return code other than JIM_RETURN
, the value
for the key -code
will be set to the return code. For JIM_RETURN
it will be set to the code given in return
-code
. Additionally,
for the return code JIM_ERR
, the value of the key -errorinfo
will contain the current stack trace (the same result as info
stacktrace
),
the value of the key -errorcode
will contain the
same value as the global variable $::errorCode, and the value of
the key -level
will be the current return level (see return
-level
).
This can be useful to rethrow an error:
if {[catch {...} msg opts]} {
...maybe do something with the error...
incr opts(-level)
return {*}$opts $msg
}
Normally catch
will not
catch any of the codes JIM_EXIT
, JIM_EVAL
or JIM_SIGNAL
.
The set of codes which will be caught may be modified by specifying the one more codes before
command
.
e.g. To catch JIM_EXIT
but not JIM_BREAK
or JIM_CONTINUE
catch -exit -nobreak -nocontinue -- { ... }
The use of --
is optional. It signifies that no more return code options follow.
cd
cd dirName
Change the current working directory to dirName
.
Returns an empty string.
This command can potentially be disruptive to an application, so it may be removed in some applications.
clock
-
clock seconds
-
Returns the current time as seconds since the epoch.
-
clock clicks
-
Returns the current time in "clicks", a system-dependent, high-resolution time.
-
clock microseconds
-
Returns the current time in microseconds.
-
clock milliseconds
-
Returns the current time in milliseconds.
-
clock format seconds ?-format format? ?-gmt boolean?
-
Format the given time (seconds since the epoch) according to the given format. See strftime(3) for supported formats. If no format is supplied, "%c" is used.
-
If
boolean
is true, processing is performed in UTC. Ifboolean
is false (the default), processing is performed in the local time zone. -
clock scan str -format format ?-gmt boolean?
-
Scan the given time string using the given format string. See strptime(3) for supported formats. See
clock
format
for the handling of -gmt.
NOTE Some systems such as 32-bit Linux have only a 32-bit time_t, and are therefore not year 2038 compliant.
close
close fileId
fileId close
Closes the file given by fileId
.
fileId
must be the return value from a previous invocation
of the open
command; after this command, it should not be
used anymore.
collect
collect
Normally reference garbage collection is automatically performed periodically.
However it may be run immediately with the collect
command.
See GARBAGE COLLECTION for more detail.
concat
concat arg ?arg ...?
This command treats each argument as a list and concatenates them into a single list. It permits any number of arguments. For example, the command
concat a b {c d e} {f {g h}}
will return
a b c d e f {g h}
as its result.
continue
continue
curry
alias args...
Similar to alias
except it creates an anonymous procedure (lambda) instead of
a named procedure.
the following creates a local, unnamed alias for the command info
exists
.
set e [local curry info exists]
if {[$e var]} {
...
}
curry
returns the name of the procedure.
defer
defer script
This command is a simple helper command to add a script to the $jim::defer
variable
that will run when the current proc or interpreter exits. For example:
. proc a {} { defer {puts "Leaving a"}; puts "Exit" }
. a
Exit
Leaving a
If the $jim::defer
variable exists, it is treated as a list of scripts to run
when the proc or interpreter exits.
dict
dict option ?arg...?
Performs one of several operations on dictionary values.
The option
argument determines what action is carried out by the
command. The legal options
are:
-
dict create ?key value ...?
-
Create and return a new dictionary value that contains each of the key/value mappings listed as arguments (keys and values alternating, with each key being followed by its associated value.)
-
dict exists dictionary key ?key ...?
-
Returns a boolean value indicating whether the given key (or path of keys through a set of nested dictionaries) exists in the given dictionary value. This returns a true value exactly when
dict
get
on that path will succeed. -
dict get dictionary ?key ...?
-
Given a dictionary value (first argument) and a key (second argument), this will retrieve the value for that key. Where several keys are supplied, the behaviour of the command shall be as if the result of "
dict
get $dictVal $key
" was passed as the first argument to dict get with the remaining arguments as second (and possibly subsequent) arguments. This facilitates lookups in nested dictionaries. If no keys are provided, dict would return a list containing pairs of elements in a manner similar to array get. That is, the first element of each pair would be the key and the second element would be the value for that key. It is an error to attempt to retrieve a value for a key that is not present in the dictionary. -
dict getdef dictionary ?key ...? key default
-
Alias for
dict
getwithdefault
. -
dict getwithdefault dictionary ?key ...? key default
-
Similar to
dict
get
except if no value exists in the dictionary for the give key(s), returnsdefault
instead. -
dict keys dictionary ?pattern?
-
Returns a list of the keys in the dictionary. If
pattern
is specified, then only those keys whose names matchpattern
(using STRING MATCHING rules) are included. -
dict merge ?dictionary ...?
-
Return a dictionary that contains the contents of each of the
dictionary
arguments. Where two (or more) dictionaries contain a mapping for the same key, the resulting dictionary maps that key to the value according to the last dictionary on the command line containing a mapping for that key. -
dict set dictionaryName key ?key ...? value
-
This operation takes the
name
of a variable containing a dictionary value and places an updated dictionary value in that variable containing a mapping from the given key to the given value. When multiple keys are present, this operation creates or updates a chain of nested dictionaries. -
dict size dictionary
-
Return the number of key/value mappings in the given dictionary value.
-
dict unset dictionaryName key ?key ...? value
-
This operation (the companion to
dict
set
) takes the name of a variable containing a dictionary value and places an updated dictionary value in that variable that does not contain a mapping for the given key. Where multiple keys are present, this describes a path through nested dictionaries to the mapping to remove. At least one key must be specified, but the last key on the key-path need not exist. All other components on the path must exist. -
dict with dictionaryName key ?key ...? script
-
Execute the Tcl script in
script
with the value for each key indictionaryName
mapped to a variable with the same name. Where one or more keys are given, these indicate a chain of nested dictionaries, with the innermost dictionary being the one opened out for the execution of body. MakingdictionaryName
unreadable will make the updates to the dictionary be discarded, and this also happens if the contents ofdictionaryName
are adjusted so that the chain of dictionaries no longer exists. The result ofdict
with
is (unless some kind of error occurs) the result of the evaluation of body. -
The variables are mapped in the scope enclosing the
dict
with
; it is recommended that this command only be used in a local scope (procedure). Because of this, the variables set bydict
with
will continue to exist after the command finishes (unless explicitly unset). Note that changes to the contents ofdictionaryName
only happen whenscript
terminates.
dict for, values, incr, append, lappend, update, info, replace
to be documented…
ensemble
ensemble name ?-automap? prefix
Create a single ensemble command that redirects to individual commands based on the prefix.
By default, the prefix is name
followed by a single space.
For example, consider:
proc {test open} {name} { ... }
proc {test close} {handle} { ... }
proc {test show} {handle} { ... }
ensemble test
Now the test
command has been created that redirects based on the first argument.
e.g.
test open $filename => {test open} $filename
env
env ?name? ?default?
If name
is supplied, returns the value of name
from the initial
environment (see getenv(3)). An error is returned if name
does not
exist in the environment, unless default
is supplied - in which case
that value is returned instead.
If no arguments are supplied, returns a list of all environment variables
and their values as {name value ...}
See also the global variable ::env
eof
eof fileId
fileId eof
Returns 1 if an end-of-file condition has occurred on fileId
,
0 otherwise.
fileId
must have been the return value from a previous call to open
,
or it may be stdin
, stdout
, or stderr
to refer to one of the
standard I/O channels.
error
error message ?stacktrace?
Returns a JIM_ERR
code, which causes command interpretation to be
unwound. message
is a string that is returned to the application
to indicate what went wrong.
If the stacktrace
argument is provided and is non-empty,
it is used to initialize the stacktrace.
This feature is most useful in conjunction with the catch
command:
if a caught error cannot be handled successfully, stacktrace
can be used
to return a stack trace reflecting the original point of occurrence
of the error:
catch {...} errMsg
...
error $errMsg [info stacktrace]
errorInfo
errorInfo error ?stacktrace?
Returns a human-readable representation of the given error message and stack trace. Typical usage is:
if {[catch {...} error]} {
puts stderr [errorInfo $error [info stacktrace]]
exit 1
}
See also error
.
eval
eval arg ?arg...?
eval
takes one or more arguments, which together comprise a Tcl
command (or collection of Tcl commands separated by newlines in the
usual way). eval
concatenates all its arguments in the same
fashion as the concat
command, passes the concatenated string to the
Tcl interpreter recursively, and returns the result of that
evaluation (or any error generated by it).
exec
exec arg ?arg...?
This command treats its arguments as the specification
of one or more UNIX commands to execute as subprocesses.
The commands take the form of a standard shell pipeline;
|
arguments separate commands in the
pipeline and cause standard output of the preceding command
to be piped into standard input of the next command (or |&
for
both standard output and standard error).
Under normal conditions the result of the exec
command
consists of the standard output produced by the last command
in the pipeline followed by the standard error output.
If any of the commands writes to its standard error file, then this will be included in the result after the standard output of the last command.
Note that unlike Tcl, data written to standard error does not cause
exec
to return an error.
If any of the commands in the pipeline exit abnormally or
are killed or suspended, then exec
will return an error.
If no standard error output was produced, or is redirected,
the error message will include the normal result, as above,
followed by error messages describing the abnormal terminations.
If any standard error output was produced, these abnormal termination messages are suppressed.
If the last character of the result or error message is a newline then that character is deleted from the result or error message for consistency with normal Tcl return values.
An arg
may have one of the following special forms:
-
>filename
-
The standard output of the last command in the pipeline is redirected to the file. In this situation
exec
will normally return an empty string. -
>>filename
-
As above, but append to the file.
-
>@fileId
-
The standard output of the last command in the pipeline is redirected to the given (writable) file descriptor (e.g. stdout, stderr, or the result of
open
). In this situationexec
will normally return an empty string. -
2>filename
-
The standard error of the last command in the pipeline is redirected to the file.
-
2>>filename
-
As above, but append to the file.
-
2>@fileId
-
The standard error of the last command in the pipeline is redirected to the given (writable) file descriptor.
-
2>@1
-
The standard error of the last command in the pipeline is redirected to the same file descriptor as the standard output.
-
>&filename
-
Both the standard output and standard error of the last command in the pipeline is redirected to the file.
-
>>&filename
-
As above, but append to the file.
-
<filename
-
The standard input of the first command in the pipeline is taken from the file.
-
<<string
-
The standard input of the first command is taken as the given immediate value.
-
<@fileId
-
The standard input of the first command in the pipeline is taken from the given (readable) file descriptor.
If there is no redirection of standard input, standard error or standard output, these are connected to the corresponding input or output of the application.
If the last arg
is &
then the command will be
executed in background.
In this case the standard output from the last command
in the pipeline will
go to the application’s standard output unless
redirected in the command, and error output from all
the commands in the pipeline will go to the application’s
standard error file. The return value of exec in this case
is a list of process ids (pids) in the pipeline.
Each arg
becomes one word for a command, except for
|
, <
, <<
, >
, and &
arguments, and the
arguments that follow <
, <<
, and >
.
The first word in each command is taken as the command name; the directories in the PATH environment variable are searched for an executable by the given name.
No glob
expansion or other shell-like substitutions
are performed on the arguments to commands.
If the command fails, the global $::errorCode (and the -errorcode
option in catch
) will be set to a list, as follows:
-
CHILDKILLED pid sigName msg
-
This format is used when a child process has been killed because of a signal. The pid element will be the process’s identifier (in decimal). The sigName element will be the symbolic name of the signal that caused the process to terminate; it will be one of the names from the include file signal.h, such as SIGPIPE. The msg element will be a short human-readable message describing the signal, such as "write on pipe with no readers" for SIGPIPE.
-
CHILDSUSP pid sigName msg
-
This format is used when a child process has been suspended because of a signal. The pid element will be the process’s identifier, in decimal. The sigName element will be the symbolic name of the signal that caused the process to suspend; this will be one of the names from the include file signal.h, such as SIGTTIN. The msg element will be a short human-readable message describing the signal, such as "background tty read" for SIGTTIN.
-
CHILDSTATUS pid code
-
This format is used when a child process has exited with a non-zero exit status. The pid element will be the process’s identifier (in decimal) and the code element will be the exit code returned by the process (also in decimal).
The environment for the executed command is set from $::env (unless this variable is unset, in which case the original environment is used).
exists
exists ?-var|-proc|-command|-alias? name
Checks the existence of the given variable, procedure, command
or alias respectively and returns 1 if it exists or 0 if not. This command
provides a more simplified/convenient version of info
exists
,
info
procs
and info
commands
.
If the type is omitted, a type of -var is used. The type may be abbreviated.
exit
exit ?returnCode?
Terminate the process, returning returnCode
to the
parent as the exit status.
If returnCode
isn’t specified then it defaults
to 0.
Note that exit can be caught with catch
.
expr
expr arg
Calls the expression processor to evaluate arg
, and returns
the result as a string. See the section EXPRESSIONS above.
Note that Jim supports a shorthand syntax for expr
as $(...)
The following two are identical.
set x [expr {3 * 2 + 1}]
set x $(3 * 2 + 1)
file
file option name ?arg...?
Operate on a file or a file name. name
is the name of a file.
option
indicates what to do with the file name. Any unique
abbreviation for option
is acceptable. The valid options are:
-
file atime name
-
Return a decimal string giving the time at which file
name
was last accessed. The time is measured in the standard UNIX fashion as seconds from a fixed starting time (often January 1, 1970). If the file doesn’t exist or its access time cannot be queried then an error is generated. -
file copy ?-force? source target
-
Copies file
source
to filetarget
. The source file must exist. The target file must not exist, unless-force
is specified. -
file delete ?-force? ?--? name...
-
Deletes file or directory
name
. If the file or directory doesn’t exist, nothing happens. If it can’t be deleted, an error is generated. Non-empty directories will not be deleted unless the-force
options is given. In this case no errors will be generated, even if the file/directory can’t be deleted. Use--
if there is any possibility of the first name being-force
. -
file dirname name
-
Return all of the characters in
name
up to but not including the last slash character. If there are no slashes inname
then return.
(a single dot). If the last slash inname
is its first character, then return/
. -
file executable name
-
Return 1 if file
name
is executable by the current user, 0 otherwise. -
file exists name
-
Return 1 if file
name
exists and the current user has search privileges for the directories leading to it, 0 otherwise. -
file extension name
-
Return all of the characters in
name
after and including the last dot inname
. If there is no dot inname
then return the empty string. -
file isdirectory name
-
Return 1 if file
name
is a directory, 0 otherwise. -
file isfile name
-
Return 1 if file
name
is a regular file, 0 otherwise. -
file join arg...
-
Joins multiple path components. Note that if any components is an absolute path, the preceding components are ignored. Thus
"
returnsfile
join /tmp /root""/root"
. -
file link ?-hard|-symbolic? newname target
-
Creates a hard link (default) or symbolic link from
newname
totarget
. Note that the sense of this command is the opposite offile
rename
andfile
copy
and also ofln
, but this is compatible with Tcl. An error is returned iftarget
doesn’t exist ornewname
already exists. -
file lstat name varName
-
Same as stat option (see below) except uses the
lstat
kernel call instead ofstat
. This means that ifname
refers to a symbolic link the information returned invarName
is for the link rather than the file it refers to. On systems that don’t support symbolic links this option behaves exactly the same as the stat option. -
file mkdir dir1 ?dir2...?
-
Creates each directory specified. For each pathname
dir
specified, this command will create all non-existing parent directories as well asdir
itself. If an existing directory is specified, then no action is taken and no error is returned. Trying to overwrite an existing file with a directory will result in an error. Arguments are processed in the order specified, halting at the first error, if any. -
file mtime name ?time?
-
Return a decimal string giving the time at which file
name
was last modified. The time is measured in the standard UNIX fashion as seconds from a fixed starting time (often January 1, 1970). If the file doesn’t exist or its modified time cannot be queried then an error is generated. Iftime
is given, sets the modification time of the file to the given value. -
file mtimeus name ?time_us?
-
As for
file
mtime
except the time value is in microseconds since the epoch (see alsoclock
microseconds
). Note that some platforms and some filesystems don’t support high resolution timestamps for files. -
file normalize name
-
Return the normalized path of
name
. See realpath(3). -
file owned name
-
Return 1 if file
name
is owned by the current user, 0 otherwise. -
file readable name
-
Return 1 if file
name
is readable by the current user, 0 otherwise. -
file readlink name
-
Returns the value of the symbolic link given by
name
(i.e. the name of the file it points to). Ifname
isn’t a symbolic link or its value cannot be read, then an error is returned. On systems that don’t support symbolic links this option is undefined. -
file rename ?-force? oldname newname
-
Renames the file from the old name to the new name. If
newname
already exists, an error is returned unless-force
is specified. -
file rootname name
-
Return all of the characters in
name
up to but not including the last . character in the name. Ifname
doesn’t contain a dot, then returnname
. -
file size name
-
Returns the size, in bytes, of the file
name
. -
file split name
-
Returns a list whose elements are the path components in
name
. The first element of the list will have the same path type asname
. All other elements will be relative. Path separators will be discarded. -
file stat name ?varName?
-
Invoke the stat kernel call on
name
, and return the result as a dictionary with the following keys: atime, ctime, dev, gid, ino, mode, mtime, nlink, size, type, uid, mtimeus (if supported - seefile
mtimeus
) Each element except type is a decimal string with the value of the corresponding field from the stat return structure; see the manual entry for stat for details on the meanings of the values. The type element gives the type of the file in the same form returned by the commandfile
type
. IfvarName
is specified, it is taken to be the name of an array variable and the values are also stored into the array. -
file tail name
-
Return all of the characters in
name
after the last slash. Ifname
contains no slashes then returnname
. -
file tempfile ?template?
-
Creates and returns the name of a unique temporary file. If
template
is omitted, a default template will be used to place the file in /tmp. See mkstemp(3) for the format of the template and security concerns. -
file type name
-
Returns a string giving the type of file
name
, which will be one offile
,directory
,characterSpecial
,blockSpecial
,fifo
,link
, orsocket
. -
file writable name
-
Return 1 if file
name
is writable by the current user, 0 otherwise.
The file
commands that return 0/1 results are often used in
conditional or looping commands, for example:
if {![file exists foo]} {
error {bad file name}
} else {
...
}
finalize
finalize reference ?command?
If command
is omitted, returns the finalizer command for the given reference.
Otherwise, sets a new finalizer command for the given reference. command
may be
the empty string to remove the current finalizer.
The reference must be a valid reference create with the ref
command.
See GARBAGE COLLECTION for more detail.
flush
flush fileId
fileId flush
Flushes any output that has been buffered for fileId
. fileId
must
have been the return value from a previous call to open
, or it may be
stdout
or stderr
to access one of the standard I/O streams; it must
refer to a file that was opened for writing. This command returns an
empty string.
for
for start test next body
for
is a looping command, similar in structure to the C for
statement.
The start
, next
, and body
arguments must be Tcl command strings,
and test
is an expression string.
The for
command first invokes the Tcl interpreter to execute start
.
Then it repeatedly evaluates test
as an expression; if the result is
non-zero it invokes the Tcl interpreter on body
, then invokes the Tcl
interpreter on next
, then repeats the loop. The command terminates
when test
evaluates to 0.
If a continue
command is invoked within body
then any remaining
commands in the current execution of body
are skipped; processing
continues by invoking the Tcl interpreter on next
, then evaluating
test
, and so on.
for
returns an empty string.
foreach
foreach varName list body
foreach varList list ?varList2 list2 ...? body
In this command, varName
is the name of a variable, list
is a list of values to assign to varName
, and body
is a
collection of Tcl commands.
For each field in list
(in order from left to right), foreach
assigns
the contents of the field to varName
(as if the lindex
command
had been used to extract the field), then calls the Tcl interpreter to
execute body
.
If instead of being a simple name, varList
is used, multiple assignments
are made each time through the loop, one for each element of varList
.
For example, if there are two elements in varList
and six elements in
the list, the loop will be executed three times.
If the length of the list doesn’t evenly divide by the number of elements
in varList
, the value of the remaining variables in the last iteration
of the loop are undefined.
The break
and continue
statements may be invoked inside body
,
with the same effect as in the for
command.
foreach
returns an empty string.
format
format formatString ?arg ...?
This command generates a formatted string in the same way as the
C sprintf procedure (it uses sprintf in its
implementation). formatString
indicates how to format
the result, using %
fields as in sprintf, and the additional
arguments, if any, provide values to be substituted into the result.
All of the sprintf options are valid; see the sprintf
man page for details. Each arg
must match the expected type
from the %
field in formatString
; the format
command
converts each argument to the correct type (floating, integer, etc.)
before passing it to sprintf for formatting.
The only unusual conversion is for %c
; in this case the argument
must be a decimal string, which will then be converted to the corresponding
ASCII (or UTF-8) character value.
In addition, Jim Tcl provides basic support for conversion to binary with %b
.
format
does backslash substitution on its formatString
argument, so backslash sequences in formatString
will be handled
correctly even if the argument is in braces.
The return value from format
is the formatted string.
getref
getref reference
Returns the string associated with reference
. The reference must
be a valid reference create with the ref
command.
See GARBAGE COLLECTION for more detail.
gets
gets fileId ?varName?
fileId gets ?varName?
Reads the next line from the file given by fileId
and discards
the terminating newline character.
If varName
is specified, then the line is placed in the variable
by that name and the return value is a count of the number of characters
read (not including the newline).
If the end of the file is reached before reading
any characters then -1 is returned and varName
is set to an
empty string.
If varName
is not specified then the return value will be
the line (minus the newline character) or an empty string if
the end of the file is reached before reading any characters.
An empty string will also be returned if a line contains no characters
except the newline, so eof
may have to be used to determine
what really happened.
If the last character in the file is not a newline character, then
gets
behaves as if there were an additional newline character
at the end of the file.
fileId
must be stdin
or the return value from a previous
call to open
; it must refer to a file that was opened
for reading.
glob
glob ?-nocomplain? ?-directory dir? ?-tails? ?--? pattern ?pattern ...?
This command performs filename globbing, using csh rules. The returned
value from glob
is the list of expanded filenames.
If -nocomplain
is specified as the first argument then an empty
list may be returned; otherwise an error is returned if the expanded
list is empty. The -nocomplain
argument must be provided
exactly: an abbreviation will not be accepted.
If -directory
is given, the dir
is understood to contain a
directory name to search in. This allows globbing inside directories
whose names may contain glob-sensitive characters. The returned names
include the directory name unless -tails
is specified.
If -tails
is specified, along with -directory
, the returned names
are relative to the given directory.
global
global varName ?varName ...?
This command is ignored unless a Tcl procedure is being interpreted.
If so, then it declares each given varName
to be a global variable
rather than a local one. For the duration of the current procedure
(and only while executing in the current procedure), any reference to
varName
will be bound to a global variable instead
of a local one.
An alternative to using global
is to use the ::
prefix
to explicitly name a variable in the global scope.
if
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
The if
command evaluates expr1
as an expression (in the same way
that expr
evaluates its argument). The value of the expression must
be numeric; if it is non-zero then body1
is executed by passing it to
the Tcl interpreter.
Otherwise expr2
is evaluated as an expression and if it is non-zero
then body2
is executed, and so on.
If none of the expressions evaluates to non-zero then bodyN
is executed.
The then
and else
arguments are optional "noise words" to make the
command easier to read.
There may be any number of elseif
clauses, including zero. bodyN
may also be omitted as long as else
is omitted too.
The return value from the command is the result of the body script that
was executed, or an empty string if none of the expressions was non-zero
and there was no bodyN
.
incr
incr varName ?increment?
Increment the value stored in the variable whose name is varName
.
The value of the variable must be integral.
If increment
is supplied then its value (which must be an
integer expression) is added to the value of variable varName
; otherwise
1 is added to varName
.
The new value is stored as a decimal string in variable varName
and also returned as result.
If the variable does not exist, the variable is implicitly created
and set to 0
first.
info
-
info option ?arg...?
-
Provide information about various internals to the Tcl interpreter. The legal
option
's (which may be abbreviated) are: -
info args procname
-
Returns a list containing the names of the arguments to procedure
procname
, in order.procname
must be the name of a Tcl command procedure. -
info alias command
-
command
must be an alias created withalias
. In which case the target command and arguments, as passed toalias
are returned. Seeexists
-alias
-
info body procname
-
Returns the body of procedure
procname
.procname
must be the name of a Tcl command procedure. -
info channels
-
info commands ?pattern?
-
If
pattern
isn’t specified, returns a list of names of all the Tcl commands, including both the built-in commands written in C and the command procedures defined using theproc
command. Ifpattern
is specified, only those names matchingpattern
(using STRING MATCHING rules) are returned. -
info complete command ?missing?
-
Returns 1 if
command
is a complete Tcl command in the sense of having no unclosed quotes, braces, brackets or array element names, If the command doesn’t appear to be complete then 0 is returned. This command is typically used in line-oriented input environments to allow users to type in commands that span multiple lines; if the command isn’t complete, the script can delay evaluating it until additional lines have been typed to complete the command. IfvarName
is specified, the missing character is stored in the variable with that name. -
info exists varName
-
Returns 1 if the variable named
varName
exists in the current context (either as a global or local variable), returns 0 otherwise. -
info frame ?number?
-
Note: This command has changed as of Jim version 0.82 to be more Tcl-compatible.
-
If
number
is not specified, this command returns a number giving the evaluation level of the invoking command (1 when invoked a the top level). -
If
number
is positive then it selects a particular evaluation level (1 refers to the top-most evaluation level, 2 to the command it called, and so on); otherwise it gives a level relative to the current evaluation level (0 refers to the current command (info frame), -1 to its caller, and so on). In this case, the command returns a dictionary containing the folllowing keys: -
type - always
"source"
-
file - file name where the command was invoked (may be empty if not known)
-
line - line number where the command was invoked (may be 0 if not known)
-
cmd - the command (as a list) executing at the given level
-
proc - if within a proc, the name of the proc (omitted if not within a proc)
-
level - the evaluation level
-
info globals ?pattern?
-
If
pattern
isn’t specified, returns a list of all the names of currently-defined global variables. Ifpattern
is specified, only those names matchingpattern
(using STRING MATCHING rules) are returned. -
info hostname
-
An alias for
os.gethostname
for compatibility with Tcl 6.x -
info level ?number?
-
If
number
is not specified, this command returns a number giving the stack level of the invoking procedure, or 0 if the command is invoked at top-level. Ifnumber
is specified, then the result is a list consisting of the name and arguments for the procedure call at levelnumber
on the stack. Ifnumber
is positive then it selects a particular stack level (1 refers to the top-most active procedure, 2 to the procedure it called, and so on); otherwise it gives a level relative to the current level (0 refers to the current procedure, -1 to its caller, and so on). See theuplevel
command for more information on what stack levels mean. -
info locals ?pattern?
-
If
pattern
isn’t specified, returns a list of all the names of currently-defined local variables, including arguments to the current procedure, if any. Variables defined with theglobal
andupvar
commands will not be returned. Ifpattern
is specified, only those names matchingpattern
(using STRING MATCHING rules) are returned. -
info nameofexecutable
-
Returns the name of the binary file from which the application was invoked. A full path will be returned, unless the path can’t be determined, in which case the empty string will be returned.
-
info procs ?pattern?
-
If
pattern
isn’t specified, returns a list of all the names of Tcl command procedures. Ifpattern
is specified, only those names matchingpattern
(using STRING MATCHING rules) are returned. -
info references
-
Returns a list of all references which have not yet been garbage collected.
-
info returncodes ?code?
-
Returns a list representing the mapping of standard return codes to names. e.g.
{0 ok 1 error 2 return ...}
. If a code is given, instead returns the name for the given code. -
info script
-
If a Tcl script file is currently being evaluated (i.e. there is a call to Jim_EvalFile active or there is an active invocation of the
source
command), then this command returns the name of the innermost file being processed. Otherwise the command returns an empty string. -
info source script ?filename line?
-
With a single argument, returns the original source location of the given script as a list of
{filename linenumber}
. If the source location can’t be determined, the list{{} 0}
is returned. Iffilename
andline
are given, returns a copy ofscript
with the associate source information. This can be useful to produce useful messages fromeval
, etc. if the original source information may be lost. -
info stacktrace
-
After an error is caught with
catch
, returns the stack trace as a list of{procedure filename line ...}
. -
info statics procname
-
Returns a dictionary of the static variables of procedure
procname
.procname
must be the name of a Tcl command procedure. An empty dictionary is returned if the procedure has no static variables. -
info version
-
Returns the version number for this version of Jim in the form
x.yy
. -
info vars ?pattern?
-
If
pattern
isn’t specified, returns a list of all the names of currently-visible variables, including both locals and currently-visible globals. Ifpattern
is specified, only those names matchingpattern
(using STRING MATCHING rules) are returned.
join
join list ?joinString?
The list
argument must be a valid Tcl list. This command returns the
string formed by joining all of the elements of list
together with
joinString
separating each adjacent pair of elements.
The joinString
argument defaults to a space character.
kill
kill ?SIG|-0? pid
Sends the given signal to the process identified by pid
.
The signal may be specified by name or number in one of the following forms:
-
TERM
-
SIGTERM
-
-TERM
-
15
-
-15
The signal name may be in either upper or lower case.
The special signal name -0
simply checks that a signal could
be sent.
If no signal is specified, SIGTERM is used.
An error is raised if the signal could not be delivered.
lambda
lambda args ?statics? body
The lambda
command is identical to proc
, except rather than
creating a named procedure, it creates an anonymous procedure and returns
the name of the procedure.
See proc
and GARBAGE COLLECTION for more detail.
lappend
lappend varName value ?value value ...?
Treat the variable given by varName
as a list and append each of
the value
arguments to that list as a separate element, with spaces
between elements.
If varName
doesn’t exist, it is created as a list with elements given
by the value
arguments. lappend
is similar to append
except that
each value
is appended as a list element rather than raw text.
This command provides a relatively efficient way to build up large lists. For example,
lappend a $b
is much more efficient than
set a [concat $a [list $b]]
when $a
is long.
lassign
lassign list varName ?varName ...?
This command treats the value list
as a list and assigns successive elements from that list to
the variables given by the varName
arguments in order. If there are more variable names than
list elements, the remaining variables are set to the empty string. If there are more list elements
than variables, a list of unassigned elements is returned.
. lassign {1 2 3} a b; puts a=$a,b=$b
3
a=1,b=2
local
local cmd ?arg...?
First, local
evaluates cmd
with the given arguments. The return value must
be the name of an existing command, which is then marked as having local scope.
This means that when the current procedure exits, the specified
command is deleted. This can be useful with lambda
, local procedures or
to automatically close a filehandle.
In addition, if a the command already exists with the same name,
the existing command will be kept rather than being deleted, and may be called
via upcall
. The previous command will be restored when the current
procedure exits. See upcall
for more details.
In this example, a local procedure is created. Note that the procedure continues to have global scope while it is active.
proc outer {} {
# proc ... returns "inner" which is marked local
local proc inner {} {
# will be deleted when 'outer' exits
}
inner
...
}
In this example, the lambda is deleted at the end of the procedure rather than waiting until garbage collection.
proc outer {} {
set x [lambda inner {args} {
# will be deleted when 'outer' exits
}]
# Use 'function' here which simply returns $x
local function $x
$x ...
...
}
Also see defer
as another mechanism for cleaning up at the end of a procedure.
loop
loop var ?first? limit ?incr? body
Similar to for
except simpler and possibly more efficient.
If incr
is positive, the effect is, equivalent to:
for {set var $first} {$var < $limit} {incr var $incr} $body
While if incr
is negative, the count is downwards.
If first
is not specified, 0 is used.
If incr
is not specified, 1 is used.
Note that setting the loop variable inside the loop does not
affect the loop count.
first
, limit
and incr
may be any integer expression.
lindex
lindex list ?index …?
Treats list
as a Tcl list and returns element index
from it
(0 refers to the first element of the list).
See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for index
.
In extracting the element, lindex
observes the same rules concerning
braces and quotes and backslashes as the Tcl command interpreter; however,
variable substitution and command substitution do not occur.
If no index values are given, simply returns list
If index
is negative or greater than or equal to the number of elements
in list
, then an empty string is returned.
If additional index arguments are supplied, then each argument is used in turn to select an element from the previous indexing operation, allowing the script to select elements from sublists.
linsert
linsert list index element ?element element ...?
This command produces a new list from list
by inserting all
of the element
arguments just before the element index
of list
. Each element
argument will become
a separate element of the new list. If index
is less than
or equal to zero, then the new elements are inserted at the
beginning of the list. If index
is greater than or equal
to the number of elements in the list, then the new elements are
appended to the list.
See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for index
.
list
list arg ?arg ...?
This command returns a list comprised of all the arguments, arg
. Braces
and backslashes get added as necessary, so that the lindex
command
may be used on the result to re-extract the original arguments, and also
so that eval
may be used to execute the resulting list, with
arg1
comprising the command’s name and the other args comprising
its arguments. list
produces slightly different results than
concat
: concat
removes one level of grouping before forming
the list, while list
works directly from the original arguments.
For example, the command
list a b {c d e} {f {g h}}
will return
a b {c d e} {f {g h}}
while concat
with the same arguments will return
a b c d e f {g h}
llength
llength list
Treats list
as a list and returns the number of elements in that list.
lset
lset varName ?index ..? newValue
Sets an element in a list.
The lset
command accepts a parameter, varName
, which it interprets
as the name of a variable containing a Tcl list. It also accepts
zero or more indices into the list. Finally, it accepts a new value
for an element of varName
. If no indices are presented, the command
takes the form:
lset varName newValue
In this case, newValue replaces the old value of the variable
varName
.
When presented with a single index, the lset
command
treats the content of the varName
variable as a Tcl list. It addresses
the index’th element in it (0 refers to the first element of the
list). When interpreting the list, lset
observes the same rules
concerning braces and quotes and backslashes as the Tcl command
interpreter; however, variable substitution and command substitution
do not occur. The command constructs a new list in which the
designated element is replaced with newValue. This new list is
stored in the variable varName
, and is also the return value from
the lset
command.
If index is negative or greater than or equal to the number of
elements in $varName
, then an error occurs.
See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for index
.
If additional index arguments are supplied, then each argument is used in turn to address an element within a sublist designated by the previous indexing operation, allowing the script to alter elements in sublists. The command,
lset a 1 2 newValue
replaces element 2 of sublist 1 with newValue
.
The integer appearing in each index argument must be greater than
or equal to zero. The integer appearing in each index argument must
be strictly less than the length of the corresponding list. In other
words, the lset
command cannot change the size of a list. If an
index is outside the permitted range, an error is reported.
lmap
lmap varName list body
lmap varList list ?varList2 list2 ...? body
For example:
. lmap i {1 2 3 4 5} {expr $i*$i}
1 4 9 16 25
. lmap a {1 2 3} b {A B C} {list $a $b}
{1 A} {2 B} {3 C}
load
load filename
Loads the dynamic extension, filename
. Generally the filename should have
the extension .so
. The initialisation function for the module must be based
on the name of the file. For example loading hwaccess.so
will invoke
the initialisation function, Jim_hwaccessInit
. Normally the load
command
should not be used directly. Instead it is invoked automatically by package
require
.
lrange
lrange list first last
list
must be a valid Tcl list. This command will return a new
list consisting of elements first
through last
, inclusive.
See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for first
and last
.
If last
is greater than or equal to the number of elements
in the list, then it is treated as if it were end
.
If first
is greater than last
then an empty string
is returned.
lreplace
lreplace list first last ?element element ...?
Returns a new list formed by replacing one or more elements of
list
with the element
arguments.
first
gives the index in list
of the first element
to be replaced.
If first
is less than zero then it refers to the first
element of list
; the element indicated by first
must exist in the list.
last
gives the index in list
of the last element
to be replaced; it must be greater than or equal to first
.
See STRING AND LIST INDEX SPECIFICATIONS for all allowed forms for first
and last
.
The element
arguments specify zero or more new arguments to
be added to the list in place of those that were deleted.
Each element
argument will become a separate element of
the list.
If no element
arguments are specified, then the elements
between first
and last
are simply deleted.
lrepeat
lrepeat number element1 ?element2 ...?
Build a list by repeating elements number
times (which must be
a positive integer).
. lrepeat 3 a b
a b a b a b
lreverse
lreverse list
Returns the list in reverse order.
. lreverse {1 2 3}
3 2 1
lsearch
lsearch ?options? list pattern
This command searches the elements list
to see if one of them matches pattern
. If so, the
command returns the index of the first matching element (unless the options -all
, -inline
or -bool
are
specified.) If not, the command returns -1. The option arguments indicates how the elements of
the list are to be matched against pattern and must have one of the values below:
Note that this command is different from Tcl in that default match type is -exact
rather than -glob
.
-
-exact
-
pattern
is a literal string that is compared for exact equality against each list element. This is the default. -
-glob
-
pattern
is a glob-style pattern which is matched against each list element using STRING MATCHING rules. -
-regexp
-
pattern
is treated as a regular expression and matched against each list element using REGULAR EXPRESSIONS rules. -
-command cmdname
-
cmdname
is a command which is used to match the pattern against each element of the list. It is invoked ascmdname ?-nocase? pattern listvalue
and should return 1 for a match, or 0 for no match. -
-all
-
Changes the result to be the list of all matching indices (or all matching values if
-inline
is specified as well). If indices are returned, the indices will be in numeric order. If values are returned, the order of the values will be the order of those values within the input list. -
-inline
-
The matching value is returned instead of its index (or an empty string if no value matches). If
-all
is also specified, then the result of the command is the list of all values that matched. The-inline
and-bool
options are mutually exclusive. -
-bool
-
Changes the result to 1 if a match was found, or 0 otherwise. If
-all
is also specified, the result will be a list of 0 and 1 for each element of the list depending upon whether the corresponding element matches. The-inline
and-bool
options are mutually exclusive. -
-not
-
This negates the sense of the match, returning the index (or value if
-inline
is specified) of the first non-matching value in the list. If-bool
is also specified, the 0 will be returned if a match is found, or 1 otherwise. If-all
is also specified, non-matches will be returned rather than matches. -
-nocase
-
Causes comparisons to be handled in a case-insensitive manner.
-
-index indexList
-
This option is designed for use when searching within nested lists. The indexList gives a path of indices (much as might be used with the lindex or lset commands) within each element to allow the location of the term being matched against.
-
-stride strideLength
-
If this option is specified, the list is treated as consisting of groups of strideLength elements and the groups are searched by either their first element or, if the
-index
option is used, by the element within each group given by the first index passed to-index
(which is then ignored by-index
). The resulting index always points to the first element in a group. -
The list length must be an integer multiple of strideLength, which in turn must be at least 1. A strideLength of 1 is the default and indicates no grouping.
lsort
lsort ?options? list
Sort the elements of list
, returning a new list in sorted order.
By default, ASCII (or UTF-8) sorting is used, with the result in increasing order.
Note that only one sort type may be selected with -integer
, -real
, -nocase
or -command
with last option being used.
-
-integer
-
Sort using numeric (integer) comparison.
-
-real
-
Sort using floating point comparison.
-
-nocase
-
Sort using using string comparison without regard for case.
-
-command cmdname
-
cmdname
is treated as a command name. For each comparison,cmdname $value1 $value2
is called which should compare the values and return an integer less than, equal to, or greater than zero if the$value1
is to be considered less than, equal to, or greater than$value2
, respectively. -
-increasing
-
The resulting list is in ascending order, from smallest/lowest to largest/highest. This is the default and does not need to be specified.
-
-decreasing
-
The resulting list is in the opposite order to what it would be otherwise.
-
-unique
-
Only the last set of duplicate elements found in the list will be retained. Note that duplicates are determined relative to the comparison used in the sort. Thus if
-index 0
is used,{1 a}
and{1 b}
would be considered duplicates and only the second element,{1 b}
, would be retained. -
-index indexList
-
This option is designed for use when sorting nested lists. The indexList gives a path of indices (much as might be used with the lindex or lset commands) within each element to specify the value to be used for comparison.
-
-stride strideLength
-
If this option is specified, the list is treated as consisting of groups of strideLength elements and the groups are sorted by either their first element or, if the
-index
option is used, by the element within each group given by the first index passed to-index
(which is then ignored by-index
). The resulting list is once again a flat list. -
The list length must be an integer multiple of strideLength, which in turn must be at least 2.
open
open fileName ?access?
open |command-pipeline ?access?
Opens a file and returns an identifier
that may be used in future invocations
of commands like read
, puts
, and close
.
fileName
gives the name of the file to open.
The access
argument indicates the way in which the file is to be accessed.
It may have any of the following values:
-
r
-
Open the file for reading only; the file must already exist.
-
r
+ -
Open the file for both reading and writing; the file must already exist.
-
w
-
Open the file for writing only. Truncate it if it exists. If it doesn’t exist, create a new file.
-
w
+ -
Open the file for reading and writing. Truncate it if it exists. If it doesn’t exist, create a new file.
-
a
-
Open the file for writing only. The file must already exist, and the file is positioned so that new data is appended to the file.
-
a
+ -
Open the file for reading and writing. If the file doesn’t exist, create a new empty file. Set the initial access position to the end of the file.
access
defaults to r.
Additionally, if POSIX mode is supported by the underlying system, then access may insted of consistent of a list of any of the following flags, all of which have the standard POSIX meanings. In this case, the first flag must be one of RDONLY, WRONLY or RDWR.
-
RDONLY
-
Open the file for reading only.
-
WRONLY
-
Open the file for writing only.
-
RDWR
-
Open the file for both reading and writing.
-
APPEND
-
Set the file pointer to the end of the file prior to each write.
-
BINARY
-
Ignored.
-
CREAT
-
Create the file if it does not already exist (without this flag it is an error for the file not to exist).
-
EXCL
-
If CREAT is also specified, an error is returned if the file already exists.
-
NOCTTY
-
If the file is a terminal device, this flag prevents the file from becoming the controlling terminal of the process.
-
TRUNC
-
If the file exists it is truncated to zero length.
If a file is opened for both reading and writing, then seek
must be invoked between a read and a write, or vice versa.
If the first character of fileName
is "|" then the remaining
characters of fileName
are treated as a list of arguments that
describe a command pipeline to invoke, in the same style as the
arguments for exec. In this case, the channel identifier returned
by open may be used to write to the command’s input pipe or read
from its output pipe, depending on the value of access
. If write-only
access is used (e.g. access
is w), then standard output for the
pipeline is directed to the current standard output unless overridden
by the command. If read-only access is used (e.g. access
is r),
standard input for the pipeline is taken from the current standard
input unless overridden by the command.
The pid
command may be used to return the process ids of the commands
forming the command pipeline.
package
package provide name ?version?
Indicates that the current script provides the package named name
.
Note: The supplied version is ignored. All packages are registered as version 1.0
(it is simply accepted for compatibility purposes).
Any script that provides a package may include this statement as the first statement, although it is not required.
package require name ?version?
Searches for the package with the given name
by examining each path
in $::auto_path and trying to load $path/$name.so as a dynamic extension,
or $path/$name.tcl as a script package.
The first such file which is found is considered to provide the package. (The version number is ignored).
If $name.so exists, it is loaded with the load
command,
otherwise if $name.tcl exists it is loaded with the source
command.
If load
or source
fails, package
require
will fail immediately.
No further attempt will be made to locate the file.
package names
Returns a list of all known/loaded packages, including internal packages.
pid
pid
pid fileId
The first form returns the process identifier of the current process.
proc
proc name args ?statics? body
The proc
command creates a new Tcl command procedure, name
.
When the new command is invoked, the contents of body
will be executed.
Tcl interpreter. args
specifies the formal arguments to the procedure.
If specified, statics
, declares static variables which are bound to the
procedure.
See PROCEDURES for detailed information about Tcl procedures.
When a procedure is invoked, the procedure’s return value is the
value specified in a return
command. If the procedure doesn’t
execute an explicit return
, then its return value is the value
of the last command executed in the procedure’s body.
If an error occurs while executing the procedure body, then the procedure-as-a-whole will return that same error.
puts
puts ?-nonewline? ?fileId? string
fileId puts ?-nonewline? string
Writes the characters given by string
to the file given
by fileId
. fileId
must have been the return
value from a previous call to open
, or it may be
stdout
or stderr
to refer to one of the standard I/O
channels; it must refer to a file that was opened for
writing.
In the first form, if no fileId
is specified then it defaults to stdout
.
puts
normally outputs a newline character after string
,
but this feature may be suppressed by specifying the -nonewline
switch.
Output to files is buffered internally by Tcl; the flush
command may be used to force buffered characters to be output.
pipe
Creates a pair of aio
channels and returns the handles as a list: {read write}
lassign [pipe] r w
# Must close $w after exec
exec ps >@$w &
$w close
$r readable ...
pwd
pwd
Returns the path name of the current working directory.
rand
rand ?min? ?max?
Returns a random integer between min
(defaults to 0) and max
(defaults to the maximum integer).
If only one argument is given, it is interpreted as max
.
range
range ?start? end ?step?
Returns a list of integers starting at start
(defaults to 0)
and ranging up to but not including end
in steps of step
defaults to 1).
. range 5
0 1 2 3 4
. range 2 5
2 3 4
. range 2 10 4
2 6
. range 7 4 -2
7 5
Integer parameters may be any integer expression.
read
read ?-nonewline? fileId
fileId read ?-nonewline?
read fileId numBytes
fileId read numBytes
read ?-pending? fileId
fileId read ?-pending?
In the first form, all of the remaining bytes are read from the file
given by fileId
; they are returned as the result of the command.
If the -nonewline
switch is specified then the last
character of the file is discarded if it is a newline.
In the second form, the extra argument specifies how many bytes to read;
exactly this many bytes will be read and returned, unless there are fewer than
numBytes
bytes left in the file; in this case, all the remaining
bytes are returned.
The third form is currently only useful with SSL sockets. It reads at least 1 byte and then any additional data that is buffered. This allows for use in an event handler. e.g.
$sock readable {
set buf [$sock read -pending]
}
This is necessary because otherwise pending data may be buffered, but
the underlying socket will not be marked readable. This featured is not
currently supported for regular sockets, and so these sockets must be
set to unbufferred ($sock buffering false
) to work in an event loop.
fileId
must be stdin
or the return value from a previous call
to open
; it must refer to a file that was opened for reading.
regexp
regexp ?-nocase? ?-line? ?-indices? ?-start offset? ?-all? ?-inline? ?--? exp string ?matchVar? ?subMatchVar subMatchVar ...?
Determines whether the regular expression exp
matches part or
all of string
and returns 1 if it does, 0 if it doesn’t.
See REGULAR EXPRESSIONS above for complete information on the
syntax of exp
and how it is matched against string
.
If additional arguments are specified after string
then they
are treated as the names of variables to use to return
information about which part(s) of string
matched exp
.
matchVar
will be set to the range of string
that
matched all of exp
. The first subMatchVar
will contain
the characters in string
that matched the leftmost parenthesized
subexpression within exp
, the next subMatchVar
will
contain the characters that matched the next parenthesized
subexpression to the right in exp
, and so on.
Normally, matchVar
and the each subMatchVar
are set to hold the
matching characters from string
, however see -indices
and
-inline
below.
If there are more values for subMatchVar
than parenthesized subexpressions
within exp
, or if a particular subexpression in exp
doesn’t
match the string (e.g. because it was in a portion of the expression
that wasn’t matched), then the corresponding subMatchVar
will be
set to "-1 -1"
if -indices
has been specified or to an empty
string otherwise.
The following switches modify the behaviour of regexp
-
-nocase
-
Causes upper-case and lower-case characters to be treated as identical during the matching process.
-
-line
-
Use newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning in either REs or strings. With this flag,
[^
bracket expressions and.
never match newline, an^
anchor matches the empty string after any newline in the string in addition to its normal function, and the$
anchor matches the empty string before any newline in the string in addition to its normal function. -
-indices
-
Changes what is stored in the subMatchVars. Instead of storing the matching characters from string, each variable will contain a list of two decimal strings giving the indices in string of the first and last characters in the matching range of characters.
-
-start offset
-
Specifies a character index offset into the string at which to start matching the regular expression. If
-indices
is specified, the indices will be indexed starting from the absolute beginning of the input string.offset
will be constrained to the bounds of the input string. -
-all
-
Causes the regular expression to be matched as many times as possible in the string, returning the total number of matches found. If this is specified with match variables, they will contain information for the last match only.
-
-inline
-
Causes the command to return, as a list, the data that would otherwise be placed in match variables. When using
-inline
, match variables may not be specified. If used with-all
, the list will be concatenated at each iteration, such that a flat list is always returned. For each match iteration, the command will append the overall match data, plus one element for each subexpression in the regular expression. -
--
-
Marks the end of switches. The argument following this one will be treated as
exp
even if it starts with a-
.
regsub
regsub ?-nocase? ?-all? ?-line? ?-start offset? ?--? exp string subSpec ?varName?
This command matches the regular expression exp
against
string
using the rules described in REGULAR EXPRESSIONS
above.
If varName
is specified, the commands stores string
to varName
with the substitutions detailed below, and returns the number of
substitutions made (normally 1 unless -all
is specified).
This is 0 if there were no matches.
If varName
is not specified, the substituted string will be returned
instead.
When copying string
, the portion of string
that
matched exp
is replaced with subSpec
.
If subSpec
contains a &
or \0
, then it is replaced
in the substitution with the portion of string
that
matched exp
.
If subSpec
contains a \n
, where n
is a digit
between 1 and 9, then it is replaced in the substitution with
the portion of string
that matched the n
'-th
parenthesized subexpression of exp
.
Additional backslashes may be used in subSpec
to prevent special
interpretation of &
or \0
or \n
or
backslash.
The use of backslashes in subSpec
tends to interact badly
with the Tcl parser’s use of backslashes, so it’s generally
safest to enclose subSpec
in braces if it includes
backslashes.
The following switches modify the behaviour of regsub
-
-nocase
-
Upper-case characters in
string
are converted to lower-case before matching againstexp
; however, substitutions specified bysubSpec
use the original unconverted form ofstring
. -
-all
-
All ranges in
string
that matchexp
are found and substitution is performed for each of these ranges, rather than only the first. The&
and\n
sequences are handled for each substitution using the information from the corresponding match. -
-line
-
Use newline-sensitive matching. By default, newline is a completely ordinary character with no special meaning in either REs or strings. With this flag,
[
bracket expressions and.
never match newline, ananchor matches the empty string after any newline in the string in addition to its normal function, and the
$
anchor matches the empty string before any newline in the string in addition to its normal function. -
-start offset
-
Specifies a character index offset into the string at which to start matching the regular expression.
offset
will be constrained to the bounds of the input string. -
--
-
Marks the end of switches. The argument following this one will be treated as
exp
even if it starts with a-
.
ref
ref string tag ?finalizer?
Create a new reference containing string
of type tag
.
If finalizer
is specified, it is a command which will be invoked
when the a garbage collection cycle runs and this reference is
no longer accessible.
The finalizer is invoked as:
finalizer reference string
See GARBAGE COLLECTION for more detail.
rename
rename oldName newName
Rename the command that used to be called oldName
so that it
is now called newName
. If newName
is an empty string
(e.g. {}) then oldName
is deleted. The rename
command
returns an empty string as result.
return
return ?-code code? ?-errorinfo stacktrace? ?-errorcode errorcode? ?-level n? ?value?
Return immediately from the current procedure (or top-level command
or source
command), with value
as the return value. If value
is not specified, an empty string will be returned as result.
If -code
is specified (as either a number or ok, error, break,
continue, signal, return or exit), this code will be used instead
of JIM_OK
. This is generally useful when implementing flow of control
commands.
If -level
is specified and greater than 1, it has the effect of delaying
the new return code from -code
. This is useful when rethrowing an error
from catch
. See the implementation of try/catch in tclcompat.tcl for
an example of how this is done.
Note: The following options are only used when -code
is JIM_ERR.
If -errorinfo
is specified (as returned from info
stacktrace
)
it is used to initialize the stacktrace.
If -errorcode
is specified, it is used to set the global variable $::errorCode.
scan
scan string format varName1 ?varName2 ...?
This command parses fields from an input string in the same fashion
as the C sscanf procedure. string
gives the input to be parsed
and format
indicates how to parse it, using % fields as in
sscanf. All of the sscanf options are valid; see the sscanf
man page for details. Each varName
gives the name of a variable;
when a field is scanned from string
, the result is converted back
into a string and assigned to the corresponding varName
. The
only unusual conversion is for %c. For %c conversions a single
character value is converted to a decimal string, which is then
assigned to the corresponding varName
; no field width may be
specified for this conversion.
seek
seek fileId offset ?origin?
fileId seek offset ?origin?
Change the current access position for fileId
.
The offset
and origin