Tcl8.4.19/Tk8.4.19 Manual - Le Wiki tcl francophonewfr.tcl.tk/fichiers/Doc/tcl8.4.19.pdf ·...

1196
Tcl8.4.19/Tk8.4.19 Manual

Transcript of Tcl8.4.19/Tk8.4.19 Manual - Le Wiki tcl francophonewfr.tcl.tk/fichiers/Doc/tcl8.4.19.pdf ·...

  • Tcl8.4.19/Tk8.4.19 Manual

  • Tcl8.4.19/Tk8.4.19 Manual

    Tcl/Tk ApplicationsThe interpreters which implement Tcl and Tk.

    Tcl CommandsThe commands which the tclsh interpreter implements.

    Tk CommandsThe additional commands which the wish interpreter implements.

    Tcl LibraryThe C functions which a Tcl extended C program may use.

    Tk LibraryThe additional C functions which a Tk extended C program may use.

    KeywordsThe keywords from the Tcl/Tk man pages.

    SourceMore information about these man pages.

    Copyright ' 1989-1994 The Regents of the University of California.Copyright ' 1990-1994 The Regents of the University of CaliforniaCopyright ' 1992-1999 Karl Lehenbauer and Mark DiekhansCopyright ' 1992-1999 Karl Lehenbauer and Mark Diekhans.Copyright ' 1993-1997 Bell Labs Innovations for Lucent TechnologiesCopyright ' 1994 The Australian National UniversityCopyright ' 1994-2000 Sun Microsystems, Inc.Copyright ' 1997-2000 Ajuba Solutions.Copyright ' 1997-2000 Scriptics Corporation.Copyright ' 1998 Mark Harrison.Copyright ' 1998-1999 Scriptics CorporationCopyright ' 1998-2000 Ajuba SolutionsCopyright ' 1999 Scriptics CorportationCopyright ' 2000 Jeffrey Hobbs.Copyright ' 2001 ActiveState Tool Corp.Copyright ' 2001 Kevin B. Kenny.Copyright ' 2001 Vincent DarleyCopyright ' 2001-2002 ActiveState CorporationCopyright ' 2001-2002 Donal K. FellowsCopyright ' 2001-2002 Kevin B. Kenny. All rights reserved.Copyright ' 2001-2004 ActiveState Corporation.Copyright ' 2006-2007 Daniel A. Steffen Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    Tcl8.4.19/Tk8.4.19 Manual 1

    http://www.elf.org

  • Tcl/Tk Applications

    tclsh wish

    Copyright ' 1991-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    Tcl/Tk Applications 2

  • NAME

    tclsh - Simple shell containing Tcl interpreterSYNOPSIS

    tclsh ?fileName arg arg ...?DESCRIPTIONSCRIPT FILESVARIABLES

    argcargvargv0tcl_interactive

    PROMPTSSTANDARD CHANNELSSEE ALSOKEYWORDS

    NAME

    tclsh - Simple shell containing Tcl interpreter

    SYNOPSIS

    tclsh ?fileName arg arg ...?

    DESCRIPTION

    Tclsh is a shell-like application that reads Tcl commands from its standard input or from a file and evaluates them. Ifinvoked with no arguments then it runs interactively, reading Tcl commands from standard input and printingcommand results and error messages to standard output. It runs until the exit command is invoked or until it reachesend-of-file on its standard input. If there exists a file .tclshrc (or tclshrc.tcl on the Windows platforms) in the homedirectory of the user, tclsh evaluates the file as a Tcl script just before reading the first command from standard input.

    SCRIPT FILES

    If tclsh is invoked with arguments then the first argument is the name of a script file and any additional arguments aremade available to the script as variables (see below). Instead of reading commands from standard input tclsh will readTcl commands from the named file; tclsh will exit when it reaches the end of the file. The end of the file may bemarked either by the physical end of the medium, or by the character, '\032' ('\u001a', control-Z). If this character ispresent in the file, the tclsh application will read text up to but not including the character. An application thatrequires this character in the file may safely encode it as ``\032'', ``\x1a'', or ``\u001a''; or may generate it by use ofcommands such as format or binary. There is no automatic evaluation of .tclshrc when the name of a script file ispresented on the tclsh command line, but the script file can always source it if desired.

    If you create a Tcl script in a file whose first line is

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 3

  • #!/usr/local/bin/tclsh

    then you can invoke the script file directly from your shell if you mark the file as executable. This assumes that tclshhas been installed in the default location in /usr/local/bin; if it's installed somewhere else then you'll have to modifythe above line to match. Many UNIX systems do not allow the #! line to exceed about 30 characters in length, so besure that the tclsh executable can be accessed with a short file name.

    An even better approach is to start your script files with the following three lines:

    #!/bin/sh# the next line restarts using tclsh \exec tclsh "$0" "$@"

    This approach has three advantages over the approach in the previous paragraph. First, the location of the tclsh binarydoesn't have to be hard-wired into the script: it can be anywhere in your shell search path. Second, it gets around the30-character file name limit in the previous approach. Third, this approach will work even if tclsh is itself a shellscript (this is done on some systems in order to handle multiple architectures or operating systems: the tclsh scriptselects one of several binaries to run). The three lines cause both sh and tclsh to process the script, but the exec is onlyexecuted by sh. sh processes the script first; it treats the second line as a comment and executes the third line. Theexec statement cause the shell to stop processing and instead to start up tclsh to reprocess the entire script. When tclshstarts up, it treats all three lines as comments, since the backslash at the end of the second line causes the third line tobe treated as part of the comment on the second line.

    You should note that it is also common practise to install tclsh with its version number as part of the name. This hasthe advantage of allowing multiple versions of Tcl to exist on the same system at once, but also the disadvantage ofmaking it harder to write scripts that start up uniformly across different versions of Tcl.

    VARIABLES

    Tclsh sets the following Tcl variables:

    argcContains a count of the number of arg arguments (0 if none), not including the name of the script file.

    argvContains a Tcl list whose elements are the arg arguments, in order, or an empty string if there are no argarguments.

    argv0Contains fileName if it was specified. Otherwise, contains the name by which tclsh was invoked.

    tcl_interactiveContains 1 if tclsh is running interactively (no fileName was specified and standard input is a terminal-likedevice), 0 otherwise.

    PROMPTS

    When tclsh is invoked interactively it normally prompts for each command with ``% ''. You can change the prompt bysetting the variables tcl_prompt1 and tcl_prompt2. If variable tcl_prompt1 exists then it must consist of a Tcl script

    Tcl8.4.19/Tk8.4.19 Manual

    VARIABLES 4

  • to output a prompt; instead of outputting a prompt tclsh will evaluate the script in tcl_prompt1. The variabletcl_prompt2 is used in a similar way when a newline is typed but the current command isn't yet complete; iftcl_prompt2 isn't set then no prompt is output for incomplete commands.

    STANDARD CHANNELS

    See Tcl_StandardChannels for more explanations.

    SEE ALSO

    fconfigure, tclvars

    KEYWORDS

    argument, interpreter, prompt, script file, shell

    Copyright ' 1993 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    STANDARD CHANNELS 5

  • NAME

    wish - Simple windowing shellSYNOPSIS

    wish ?fileName arg arg ...?OPTIONS

    -colormap new-display display-geometry geometry-name name-sync-use id-visual visual- -

    DESCRIPTIONOPTIONSAPPLICATION NAME AND CLASSVARIABLES

    argcargvargv0geometrytcl_interactive

    SCRIPT FILESPROMPTSKEYWORDS

    NAME

    wish - Simple windowing shell

    SYNOPSIS

    wish ?fileName arg arg ...?

    OPTIONS

    -colormap newSpecifies that the window should have a new private colormap instead of using the default colormap for thescreen.

    -display displayDisplay (and screen) on which to display window.

    -geometry geometryInitial geometry to use for window. If this option is specified, its value is stored in the geometry globalvariable of the application's Tcl interpreter.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 6

  • -name nameUse name as the title to be displayed in the window, and as the name of the interpreter for send commands.

    -syncExecute all X server commands synchronously, so that errors are reported immediately. This will result inmuch slower execution, but it is useful for debugging.

    -use idSpecifies that the main window for the application is to be embedded in the window whose identifier is id,instead of being created as an independent toplevel window. Id must be specified in the same way as the valuefor the -use option for toplevel widgets (i.e. it has a form like that returned by the winfo id command).

    -visual visualSpecifies the visual to use for the window. Visual may have any of the forms supported by the Tk_GetVisualprocedure.

    - -Pass all remaining arguments through to the script's argv variable without interpreting them. This provides amechanism for passing arguments such as -name to a script instead of having wish interpret them.

    DESCRIPTION

    Wish is a simple program consisting of the Tcl command language, the Tk toolkit, and a main program that readscommands from standard input or from a file. It creates a main window and then processes Tcl commands. If wish isinvoked with no arguments, or with a first argument that starts with ``-'', then it reads Tcl commands interactivelyfrom standard input. It will continue processing commands until all windows have been deleted or until end-of-file isreached on standard input. If there exists a file .wishrc in the home directory of the user, wish evaluates the file as aTcl script just before reading the first command from standard input.

    If wish is invoked with an initial fileName argument, then fileName is treated as the name of a script file. Wish willevaluate the script in fileName (which presumably creates a user interface), then it will respond to events until allwindows have been deleted. Commands will not be read from standard input. There is no automatic evaluation of.wishrc when the name of a script file is presented on the wish command line, but the script file can always source itif desired.

    OPTIONS

    Wish automatically processes all of the command-line options described in the OPTIONS summary above. Any othercommand-line arguments besides these are passed through to the application using the argc and argv variablesdescribed later.

    APPLICATION NAME AND CLASS

    The name of the application, which is used for purposes such as send commands, is taken from the -name option, if itis specified; otherwise it is taken from fileName, if it is specified, or from the command name by which wish wasinvoked. In the last two cases, if the name contains a ``/'' character, then only the characters after the last slash are usedas the application name.

    The class of the application, which is used for purposes such as specifying options with a RESOURCE_MANAGER

    Tcl8.4.19/Tk8.4.19 Manual

    DESCRIPTION 7

  • property or .Xdefaults file, is the same as its name except that the first letter is capitalized.

    VARIABLES

    Wish sets the following Tcl variables:

    argcContains a count of the number of arg arguments (0 if none), not including the options described above.

    argvContains a Tcl list whose elements are the arg arguments that follow a - - option or don't match any of theoptions described in OPTIONS above, in order, or an empty string if there are no such arguments.

    argv0Contains fileName if it was specified. Otherwise, contains the name by which wish was invoked.

    geometryIf the -geometry option is specified, wish copies its value into this variable. If the variable still exists afterfileName has been evaluated, wish uses the value of the variable in a wm geometry command to set the mainwindow's geometry.

    tcl_interactiveContains 1 if wish is reading commands interactively (fileName was not specified and standard input is aterminal-like device), 0 otherwise.

    SCRIPT FILES

    If you create a Tcl script in a file whose first line is

    #!/usr/local/bin/wish

    then you can invoke the script file directly from your shell if you mark it as executable. This assumes that wish hasbeen installed in the default location in /usr/local/bin; if it's installed somewhere else then you'll have to modify theabove line to match. Many UNIX systems do not allow the #! line to exceed about 30 characters in length, so be surethat the wish executable can be accessed with a short file name.

    An even better approach is to start your script files with the following three lines:

    #!/bin/sh# the next line restarts using wish \exec wish "$0" "$@"

    This approach has three advantages over the approach in the previous paragraph. First, the location of the wish binarydoesn't have to be hard-wired into the script: it can be anywhere in your shell search path. Second, it gets around the30-character file name limit in the previous approach. Third, this approach will work even if wish is itself a shellscript (this is done on some systems in order to handle multiple architectures or operating systems: the wish scriptselects one of several binaries to run). The three lines cause both sh and wish to process the script, but the exec is onlyexecuted by sh. sh processes the script first; it treats the second line as a comment and executes the third line. Theexec statement cause the shell to stop processing and instead to start up wish to reprocess the entire script. When wishstarts up, it treats all three lines as comments, since the backslash at the end of the second line causes the third line to

    Tcl8.4.19/Tk8.4.19 Manual

    VARIABLES 8

  • be treated as part of the comment on the second line.

    The end of a script file may be marked either by the physical end of the medium, or by the character, '\032' ('\u001a',control-Z). If this character is present in the file, the wish application will read text up to but not including thecharacter. An application that requires this character in the file may encode it as ``\032'', ``\x1a'', or ``\u001a''; or maygenerate it by use of commands such as format or binary.

    PROMPTS

    When wish is invoked interactively it normally prompts for each command with ``% ''. You can change the prompt bysetting the variables tcl_prompt1 and tcl_prompt2. If variable tcl_prompt1 exists then it must consist of a Tcl scriptto output a prompt; instead of outputting a prompt wish will evaluate the script in tcl_prompt1. The variabletcl_prompt2 is used in a similar way when a newline is typed but the current command isn't yet complete; iftcl_prompt2 isn't set then no prompt is output for incomplete commands.

    KEYWORDS

    shell, toolkit

    Copyright ' 1991-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    PROMPTS 9

  • Tcl Commands

    Safe Base encoding if pid switch

    Tcl eof incr pkg::create tcl_endOfWord

    after error info pkg_mkIndex tcl_findLibrary

    append eval interp proc tcl_startOfNextWord

    array exec join puts tcl_startOfPreviousWord

    auto_execok exit lappend pwd tcl_wordBreakAfter

    auto_import expr lindex re_syntax tcl_wordBreakBefore

    auto_load fblocked linsert read tcltest

    auto_mkindex fconfigure list regexp tclvars

    auto_mkindex_old fcopy llength registry tell

    auto_qualify file load regsub time

    auto_reset fileevent lrange rename trace

    bgerror filename lreplace resource unknown

    binary flush lsearch return unset

    break for lset scan update

    catch foreach lsort seek uplevel

    cd format memory set upvar

    clock gets msgcat socket variable

    close glob namespace source vwait

    concat global open split while

    continue history package string

    dde http parray subst

    Copyright ' 1990-1994 The Regents of the University of CaliforniaCopyright ' 1990-1994 The Regents of the University of California.Copyright ' 1992-1995 Karl Lehenbauer and Mark Diekhans.Copyright ' 1992-1999 Karl Lehenbauer and Mark DiekhansCopyright ' 1993-1997 Bell Labs Innovations for Lucent TechnologiesCopyright ' 1994-2000 Sun Microsystems, Inc.Copyright ' 1998 Mark Harrison.Copyright ' 1998-1999 Scriptics CorporationCopyright ' 1998-2000 Ajuba SolutionsCopyright ' 1998-2000 Ajuba Solutions.Copyright ' 1998-2000 Scriptics Corporation.Copyright ' 2001 Donal K. FellowsCopyright ' 2001 Kevin B. Kenny. All rights reserved.Copyright ' 2001-2004 ActiveState Corporation.Copyright ' 2002 ActiveState CorporationCopyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    Tcl Commands 10

  • NAME

    Tcl - Tool Command LanguageSYNOPSIS

    Summary of Tcl language syntax.DESCRIPTION

    [1] Commands.[2] Evaluation.[3] Words.[4] Double quotes.[5] Braces.[6] Command substitution.[7] Variable substitution.

    $name$name(index)${name}

    [8] Backslash substitution.\a\b\f\n\r\t\v\whiteSpace\\\ooo\xhh\uhhhh

    [9] Comments.[10] Order of substitution.[11] Substitution and word boundaries.

    NAME

    Tcl - Tool Command Language

    SYNOPSIS

    Summary of Tcl language syntax.

    DESCRIPTION

    The following rules define the syntax and semantics of the Tcl language:

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 11

  • [1] Commands.A Tcl script is a string containing one or more commands. Semi-colons and newlines are command separatorsunless quoted as described below. Close brackets are command terminators during command substitution (seebelow) unless quoted.

    [2] Evaluation.A command is evaluated in two steps. First, the Tcl interpreter breaks the command into words and performssubstitutions as described below. These substitutions are performed in the same way for all commands. Thefirst word is used to locate a command procedure to carry out the command, then all of the words of thecommand are passed to the command procedure. The command procedure is free to interpret each of its wordsin any way it likes, such as an integer, variable name, list, or Tcl script. Different commands interpret theirwords differently.

    [3] Words.Words of a command are separated by white space (except for newlines, which are command separators).

    [4] Double quotes.If the first character of a word is double-quote (``"'') then the word is terminated by the next double-quotecharacter. If semi-colons, close brackets, or white space characters (including newlines) appear between thequotes then they are treated as ordinary characters and included in the word. Command substitution, variablesubstitution, and backslash substitution are performed on the characters between the quotes as describedbelow. The double-quotes are not retained as part of the word.

    [5] Braces.If the first character of a word is an open brace (``{'') then the word is terminated by the matching close brace(``}''). Braces nest within the word: for each additional open brace there must be an additional close brace(however, if an open brace or close brace within the word is quoted with a backslash then it is not counted inlocating the matching close brace). No substitutions are performed on the characters between the bracesexcept for backslash-newline substitutions described below, nor do semi-colons, newlines, close brackets, orwhite space receive any special interpretation. The word will consist of exactly the characters between theouter braces, not including the braces themselves.

    [6] Command substitution.If a word contains an open bracket (``['') then Tcl performs command substitution. To do this it invokes theTcl interpreter recursively to process the characters following the open bracket as a Tcl script. The script maycontain any number of commands and must be terminated by a close bracket (``]''). The result of the script(i.e. the result of its last command) is substituted into the word in place of the brackets and all of thecharacters between them. There may be any number of command substitutions in a single word. Commandsubstitution is not performed on words enclosed in braces.

    [7] Variable substitution.If a word contains a dollar-sign (``$'') followed by one of the forms described below, then Tcl performsvariable substitution: the dollar-sign and the following characters are replaced in the word by the value of avariable. Variable substitution may take any of the following forms:

    $nameName is the name of a scalar variable; the name is a sequence of one or more characters that are aletter, digit, underscore, or namespace separators (two or more colons).

    $name(index)Name gives the name of an array variable and index gives the name of an element within that array.Name must contain only letters, digits, underscores, and namespace separators, and may be an emptystring. Command substitutions, variable substitutions, and backslash substitutions are performed on

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 12

  • the characters of index.${name}

    Name is the name of a scalar variable. It may contain any characters whatsoever except for closebraces.

    There may be any number of variable substitutions in a single word. Variable substitution is not performed onwords enclosed in braces.

    [8] Backslash substitution.If a backslash (``\'') appears within a word then backslash substitution occurs. In all cases but those describedbelow the backslash is dropped and the following character is treated as an ordinary character and included inthe word. This allows characters such as double quotes, close brackets, and dollar signs to be included inwords without triggering special processing. The following table lists the backslash sequences that arehandled specially, along with the value that replaces each sequence.

    \aAudible alert (bell) (0x7).

    \bBackspace (0x8).

    \fForm feed (0xc).

    \nNewline (0xa).

    \rCarriage-return (0xd).

    \tTab (0x9).

    \vVertical tab (0xb).

    \whiteSpaceA single space character replaces the backslash, newline, and all spaces and tabs after the newline.This backslash sequence is unique in that it is replaced in a separate pre-pass before the command isactually parsed. This means that it will be replaced even when it occurs between braces, and theresulting space will be treated as a word separator if it isn't in braces or quotes.

    \\Backslash (``\'').

    \oooThe digits ooo (one, two, or three of them) give an eight-bit octal value for the Unicode character thatwill be inserted. The upper bits of the Unicode character will be 0.

    \xhhThe hexadecimal digits hh give an eight-bit hexadecimal value for the Unicode character that will beinserted. Any number of hexadecimal digits may be present; however, all but the last two are ignored(the result is always a one-byte quantity). The upper bits of the Unicode character will be 0.

    \uhhhhThe hexadecimal digits hhhh (one, two, three, or four of them) give a sixteen-bit hexadecimal valuefor the Unicode character that will be inserted.

    Backslash substitution is not performed on words enclosed in braces, except for backslash-newline asdescribed above.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 13

  • [9] Comments.If a hash character (``#'') appears at a point where Tcl is expecting the first character of the first word of acommand, then the hash character and the characters that follow it, up through the next newline, are treated asa comment and ignored. The comment character only has significance when it appears at the beginning of acommand.

    [10] Order of substitution.Each character is processed exactly once by the Tcl interpreter as part of creating the words of a command.For example, if variable substitution occurs then no further substitutions are performed on the value of thevariable; the value is inserted into the word verbatim. If command substitution occurs then the nestedcommand is processed entirely by the recursive call to the Tcl interpreter; no substitutions are performedbefore making the recursive call and no additional substitutions are performed on the result of the nestedscript.

    Substitutions take place from left to right, and each substitution is evaluated completely before attempting toevaluate the next. Thus, a sequence like

    set y [set x 0][incr x][incr x]

    will always set the variable y to the value, 012.[11] Substitution and word boundaries.

    Substitutions do not affect the word boundaries of a command. For example, during variable substitution theentire value of the variable becomes part of a single word, even if the variable's value contains spaces.

    Copyright ' 1993 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 14

  • NAME

    after - Execute a command after a time delaySYNOPSIS

    after msafter ms ?script script script ...?after cancel idafter cancel script script script ...after idle ?script script script ...?after info ?id?

    DESCRIPTIONafter msafter ms ?script script script ...?after cancel idafter cancel script script ...after idle script ?script script ...?after info ?id?

    EXAMPLESSEE ALSOKEYWORDS

    NAME

    after - Execute a command after a time delay

    SYNOPSIS

    after msafter ms ?script script script ...?after cancel idafter cancel script script script ...after idle ?script script script ...?after info ?id?

    DESCRIPTION

    This command is used to delay execution of the program or to execute a command in background sometime in thefuture. It has several forms, depending on the first argument to the command:

    after msMs must be an integer giving a time in milliseconds. The command sleeps for ms milliseconds and thenreturns. While the command is sleeping the application does not respond to events.

    after ms ?script script script ...?In this form the command returns immediately, but it arranges for a Tcl command to be executed msmilliseconds later as an event handler. The command will be executed exactly once, at the given time. The

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 15

  • delayed command is formed by concatenating all the script arguments in the same fashion as the concatcommand. The command will be executed at global level (outside the context of any Tcl procedure). If anerror occurs while executing the delayed command then the bgerror mechanism is used to report the error.The after command returns an identifier that can be used to cancel the delayed command using after cancel.

    after cancel idCancels the execution of a delayed command that was previously scheduled. Id indicates which commandshould be canceled; it must have been the return value from a previous after command. If the command givenby id has already been executed then the after cancel command has no effect.

    after cancel script script ...This command also cancels the execution of a delayed command. The script arguments are concatenatedtogether with space separators (just as in the concat command). If there is a pending command that matchesthe string, it is cancelled and will never be executed; if no such command is currently pending then the aftercancel command has no effect.

    after idle script ?script script ...?Concatenates the script arguments together with space separators (just as in the concat command), andarranges for the resulting script to be evaluated later as an idle callback. The script will be run exactly once,the next time the event loop is entered and there are no events to process. The command returns an identifierthat can be used to cancel the delayed command using after cancel. If an error occurs while executing thescript then the bgerror mechanism is used to report the error.

    after info ?id?This command returns information about existing event handlers. If no id argument is supplied, the commandreturns a list of the identifiers for all existing event handlers created by the after command for this interpreter.If id is supplied, it specifies an existing handler; id must have been the return value from some previous call toafter and it must not have triggered yet or been cancelled. In this case the command returns a list with twoelements. The first element of the list is the script associated with id, and the second element is either idle ortimer to indicate what kind of event handler it is.

    The after ms and after idle forms of the command assume that the application is event driven: the delayed commandswill not be executed unless the application enters the event loop. In applications that are not normally event-driven,such as tclsh, the event loop can be entered with the vwait and update commands.

    EXAMPLES

    This defines a command to make Tcl do nothing at all for N seconds:

    proc sleep {N} {after [expr {int($N * 1000)}]

    }

    This arranges for the command wake_up to be run in eight hours (providing the event loop is active at that time):

    after [expr {1000 * 60 * 60 * 8}] wake_up

    The following command can be used to do long-running calculations (as represented here by ::my_calc::one_step,which is assumed to return a boolean indicating whether another step should be performed) in a step-by-step fashion,though the calculation itself needs to be arranged so it can work step-wise. This technique is extra careful to ensure

    Tcl8.4.19/Tk8.4.19 Manual

    EXAMPLES 16

  • that the event loop is not starved by the rescheduling of processing steps (arranging for the next step to be done usingan already-triggered timer event only when the event queue has been drained) and is useful when you want to ensurethat a Tk GUI remains responsive during a slow task.

    proc doOneStep {} { if {[::my_calc::one_step]} {

    after idle [list after 0 doOneStep] }}doOneStep

    SEE ALSO

    bgerror, concat, update, vwait

    KEYWORDS

    cancel, delay, idle callback, sleep, time

    Copyright ' 1990-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 17

  • NAME

    append - Append to variable

    SYNOPSIS

    append varName ?value value value ...?

    DESCRIPTION

    Append all of the value arguments to the current value of variable varName. If varName doesn't exist, it is given avalue equal to the concatenation of all the value arguments. The result of this command is the new value stored invariable varName. This command provides an efficient way to build up long variables incrementally. For example,``append a $b'' is much more efficient than ``set a $a$b'' if $a is long.

    EXAMPLE

    Building a string of comma-separated numbers piecemeal using a loop.

    set var 0for {set i 1} {$i

  • NAME

    array - Manipulate array variablesSYNOPSIS

    array option arrayName ?arg arg ...?DESCRIPTION

    array anymore arrayName searchIdarray donesearch arrayName searchIdarray exists arrayNamearray get arrayName ?pattern?array names arrayName ?mode? ?pattern?array nextelement arrayName searchIdarray set arrayName listarray size arrayNamearray startsearch arrayNamearray statistics arrayNamearray unset arrayName ?pattern?

    EXAMPLESSEE ALSOKEYWORDS

    NAME

    array - Manipulate array variables

    SYNOPSIS

    array option arrayName ?arg arg ...?

    DESCRIPTION

    This command performs one of several operations on the variable given by arrayName. Unless otherwise specified forindividual commands below, arrayName must be the name of an existing array variable. The option argumentdetermines what action is carried out by the command. The legal options (which may be abbreviated) are:

    array anymore arrayName searchIdReturns 1 if there are any more elements left to be processed in an array search, 0 if all elements have alreadybeen returned. SearchId indicates which search on arrayName to check, and must have been the return valuefrom a previous invocation of array startsearch. This option is particularly useful if an array has an elementwith an empty name, since the return value from array nextelement won't indicate whether the search hasbeen completed.

    array donesearch arrayName searchIdThis command terminates an array search and destroys all the state associated with that search. SearchIdindicates which search on arrayName to destroy, and must have been the return value from a previousinvocation of array startsearch. Returns an empty string.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 19

  • array exists arrayNameReturns 1 if arrayName is an array variable, 0 if there is no variable by that name or if it is a scalar variable.

    array get arrayName ?pattern?Returns a list containing pairs of elements. The first element in each pair is the name of an element inarrayName and the second element of each pair is the value of the array element. The order of the pairs isundefined. If pattern is not specified, then all of the elements of the array are included in the result. If patternis specified, then only those elements whose names match pattern (using the matching rules of string match)are included. If arrayName isn't the name of an array variable, or if the array contains no elements, then anempty list is returned.

    array names arrayName ?mode? ?pattern?Returns a list containing the names of all of the elements in the array that match pattern. Mode may be one of-exact, -glob, or -regexp. If specified, mode designates which matching rules to use to match pattern againstthe names of the elements in the array. If not specified, mode defaults to -glob. See the documentation forstring match for information on glob style matching, and the documentation for regexp for information onregexp matching. If pattern is omitted then the command returns all of the element names in the array. If thereare no (matching) elements in the array, or if arrayName isn't the name of an array variable, then an emptystring is returned.

    array nextelement arrayName searchIdReturns the name of the next element in arrayName, or an empty string if all elements of arrayName havealready been returned in this search. The searchId argument identifies the search, and must have been thereturn value of an array startsearch command. Warning: if elements are added to or deleted from the array,then all searches are automatically terminated just as if array donesearch had been invoked; this will causearray nextelement operations to fail for those searches.

    array set arrayName listSets 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 namewithin arrayName, and the following element in list is used as a new value for that array element. If thevariable arrayName does not already exist and list is empty, arrayName is created with an empty array value.

    array size arrayNameReturns a decimal string giving the number of elements in the array. If arrayName isn't the name of an arraythen 0 is returned.

    array startsearch arrayNameThis command initializes an element-by-element search through the array given by arrayName, such thatinvocations of the array nextelement command will return the names of the individual elements in the array.When the search has been completed, the array donesearch command should be invoked. The return value isa search identifier that must be used in array nextelement and array donesearch commands; it allowsmultiple searches to be underway simultaneously for the same array. It is currently more efficient and easier touse either the array get or array names, together with foreach, to iterate over all but very large arrays. Seethe examples below for how to do this.

    array statistics arrayNameReturns statistics about the distribution of data within the hashtable that represents the array. This informationincludes the number of entries in the table, the number of buckets, and the utilization of the buckets.

    array unset arrayName ?pattern?Unsets all of the elements in the array that match pattern (using the matching rules of string match). IfarrayName isn't the name of an array variable or there are no matching elements in the array, no error will beraised. If pattern is omitted and arrayName is an array variable, then the command unsets the entire array.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 20

  • The command always returns an empty string.

    EXAMPLES

    array set colorcount { red 1 green 5 blue 4 white 9}

    foreach {color count} [array get colorcount] { puts "Color: $color Count: $count" } => Color: blue Count: 4 Color: white Count: 9 Color: green Count: 5 Color: red Count: 1

    foreach color [array names colorcount] { puts "Color: $color Count: $colorcount($color)" } => Color: blue Count: 4 Color: white Count: 9 Color: green Count: 5 Color: red Count: 1

    foreach color [lsort [array names colorcount]] { puts "Color: $color Count: $colorcount($color)" } => Color: blue Count: 4 Color: green Count: 5 Color: red Count: 1 Color: white Count: 9

    array statistics colorcount => 4 entries in table, 4 buckets number of buckets with 0 entries: 1 number of buckets with 1 entries: 2 number of buckets with 2 entries: 1 number of buckets with 3 entries: 0 number of buckets with 4 entries: 0 number of buckets with 5 entries: 0 number of buckets with 6 entries: 0 number of buckets with 7 entries: 0 number of buckets with 8 entries: 0 number of buckets with 9 entries: 0 number of buckets with 10 or more entries: 0 average search distance for entry: 1.2

    Tcl8.4.19/Tk8.4.19 Manual

    EXAMPLES 21

  • SEE ALSO

    list, string, variable, trace, foreach

    KEYWORDS

    array, element names, search

    Copyright ' 1993-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 22

  • NAME

    bgerror - Command invoked to process background errors

    SYNOPSIS

    bgerror message

    DESCRIPTION

    The bgerror command doesn't exist as built-in part of Tcl. Instead, individual applications or users can define abgerror command (e.g. as a Tcl procedure) if they wish to handle background errors.

    A background error is one that occurs in an event handler or some other command that didn't originate with theapplication. For example, if an error occurs while executing a command specified with the after command, then it is abackground error. For a non-background error, the error can simply be returned up through nested Tcl commandevaluations until it reaches the top-level code in the application; then the application can report the error in whateverway it wishes. When a background error occurs, the unwinding ends in the Tcl library and there is no obvious way forTcl to report the error.

    When Tcl detects a background error, it saves information about the error and invokes the bgerror command later asan idle event handler. Before invoking bgerror, Tcl restores the errorInfo and errorCode variables to their values atthe time the error occurred, then it invokes bgerror with the error message as its only argument. Tcl assumes that theapplication has implemented the bgerror command, and that the command will report the error in a way that makessense for the application. Tcl will ignore any result returned by the bgerror command as long as no error is generated.

    If another Tcl error occurs within the bgerror command (for example, because no bgerror command has beendefined) then Tcl reports the error itself by writing a message to stderr.

    If several background errors accumulate before bgerror is invoked to process them, bgerror will be invoked once foreach error, in the order they occurred. However, if bgerror returns with a break exception, then any remaining errorsare skipped without calling bgerror.

    Tcl has no default implementation for bgerror. However, in applications using Tk there is a default bgerrorprocedure which posts a dialog box containing the error message and offers the user a chance to see a stack traceshowing where the error occurred. In addition to allowing the user to view the stack trace, the dialog provides anadditional application configurable button which may be used, for example, to save the stack trace to a file. Bydefault, this is the behavior associated with that button. This behavior can be redefined by setting the option databasevalues *ErrorDialog.function.text, to specify the caption for the function button, and*ErrorDialog.function.command, to specify the command to be run. The text of the stack trace is appended to thecommand when it is evaluated. If either of these options is set to the empty string, then the additional button will notbe displayed in the dialog.

    If you are writing code that will be used by others as part of a package or other kind of library, consider avoidingbgerror. The reason for this is that the application programmer may also want to define a bgerror, or use other code

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 23

  • that does and thus will have trouble integrating your code.

    EXAMPLE

    This bgerror procedure appends errors to a file, with a timestamp.

    proc bgerror {message} { set timestamp [clock format [clock seconds]] set fl [open mylog.txt {WRONLY CREAT APPEND}] puts $fl "$timestamp: bgerror in $::argv '$message'" close $fl}

    SEE ALSO

    after, tclvars

    KEYWORDS

    background error, reporting

    Copyright ' 1990-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    EXAMPLE 24

  • NAME

    binary - Insert and extract fields from binary stringsSYNOPSIS

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

    DESCRIPTIONBINARY FORMAT

    aAbBhHcsSiIwWfdxX@

    BINARY SCANaAbBhHcsSiIwWfdxX@

    PLATFORM ISSUES

    Tcl8.4.19/Tk8.4.19 Manual

    EXAMPLE 25

  • EXAMPLESSEE ALSOKEYWORDS

    NAME

    binary - Insert and extract fields from binary strings

    SYNOPSIS

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

    DESCRIPTION

    This command provides facilities for manipulating binary data. The first form, binary format, creates a binary stringfrom normal Tcl values. For example, given the values 16 and 22, on a 32 bit architecture, it might produce an 8-bytebinary string consisting of two 4-byte integers, one for each of the numbers. The second form of the command, binaryscan, does the opposite: it extracts data from a binary string and returns it as ordinary Tcl string values.

    BINARY FORMAT

    The binary format command generates a binary string whose layout is specified by the formatString and whosecontents come from the additional arguments. The resulting binary value is returned.

    The formatString consists of a sequence of zero or more field specifiers separated by zero or more spaces. Each fieldspecifier is a single type character followed by an optional numeric count. Most field specifiers consume oneargument to obtain the value to be formatted. The type character specifies how the value is to be formatted. The counttypically indicates how many items of the specified type are taken from the value. If present, the count is anon-negative decimal integer or *, which normally indicates that all of the items in the value are to be used. If thenumber of arguments does not match the number of fields in the format string that consume arguments, then an erroris generated.

    Here is a small example to clarify the relation between the field specifiers and the arguments:

    binary format d3d {1.0 2.0 3.0 4.0} 0.1

    The first argument is a list of four numbers, but because of the count of 3 for the associated field specifier, only thefirst three will be used. The second argument is associated with the second field specifier. The resulting binary stringcontains the four numbers 1.0, 2.0, 3.0 and 0.1.

    Each type-count pair moves an imaginary cursor through the binary data, storing bytes at the current position andadvancing the cursor to just after the last byte stored. The cursor is initially at position 0 at the beginning of the data.The type may be any one of the following characters:

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 26

  • aStores a character string of length count in the output string. Every character is taken as modulo 256 (i.e. thelow byte of every character is used, and the high byte discarded) so when storing character strings not whollyexpressible using the characters \u0000-\u00ff, the encoding convertto command should be used first if thistruncation is not desired (i.e. if the characters are not part of the ISO 8859-1 character set.) If arg has fewerthan count bytes, then additional zero bytes are used to pad out the field. If arg is longer than the specifiedlength, the extra characters will be ignored. If count is *, then all of the bytes in arg will be formatted. If countis omitted, then one character will be formatted. For example,

    binary format a7a*a alpha bravo charlie

    will return a string equivalent to alpha\000\000bravoc.A

    This form is the same as a except that spaces are used for padding instead of nulls. For example,

    binary format A6A*A alpha bravo charlie

    will return alpha bravoc.b

    Stores a string of count binary digits in low-to-high order within each byte in the output string. Arg mustcontain a sequence of 1 and 0 characters. The resulting bytes are emitted in first to last order with the bitsbeing formatted in low-to-high order within each byte. If arg has fewer than count digits, then zeros will beused for the remaining bits. If arg has more than the specified number of digits, the extra digits will beignored. If count is *, then all of the digits in arg will be formatted. If count is omitted, then one digit will beformatted. If the number of bits formatted does not end at a byte boundary, the remaining bits of the last bytewill be zeros. For example,

    binary format b5b* 11100 111000011010

    will return a string equivalent to \x07\x87\x05.B

    This form is the same as b except that the bits are stored in high-to-low order within each byte. For example,

    binary format B5B* 11100 111000011010

    will return a string equivalent to \xe0\xe1\xa0.h

    Stores a string of count hexadecimal digits in low-to-high within each byte in the output string. Arg mustcontain a sequence of characters in the set ``0123456789abcdefABCDEF''. The resulting bytes are emitted infirst to last order with the hex digits being formatted in low-to-high order within each byte. If arg has fewerthan count digits, then zeros will be used for the remaining digits. If arg has more than the specified numberof digits, the extra digits will be ignored. If count is *, then all of the digits in arg will be formatted. If count isomitted, then one digit will be formatted. If the number of digits formatted does not end at a byte boundary,the remaining bits of the last byte will be zeros. For example,

    binary format h3h* AB def

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 27

  • will return a string equivalent to \xba\x00\xed\x0f.H

    This form is the same as h except that the digits are stored in high-to-low order within each byte. For example,

    binary format H3H* ab DEF

    will return a string equivalent to \xab\x00\xde\xf0.c

    Stores one or more 8-bit integer values in the output string. If no count is specified, then arg must consist ofan integer value; otherwise arg must consist of a list containing at least count integer elements. The low-order8 bits of each integer are stored as a one-byte value at the cursor position. If count is *, then all of the integersin the list are formatted. If the number of elements in the list is fewer than count, then an error is generated. Ifthe number of elements in the list is greater than count, then the extra elements are ignored. For example,

    binary format c3cc* {3 -3 128 1} 260 {2 5}

    will return a string equivalent to \x03\xfd\x80\x04\x02\x05, whereas

    binary format c {2 5}

    will generate an error.s

    This form is the same as c except that it stores one or more 16-bit integers in little-endian byte order in theoutput string. The low-order 16-bits of each integer are stored as a two-byte value at the cursor position withthe least significant byte stored first. For example,

    binary format s3 {3 -3 258 1}

    will return a string equivalent to \x03\x00\xfd\xff\x02\x01.S

    This form is the same as s except that it stores one or more 16-bit integers in big-endian byte order in theoutput string. For example,

    binary format S3 {3 -3 258 1}

    will return a string equivalent to \x00\x03\xff\xfd\x01\x02.i

    This form is the same as c except that it stores one or more 32-bit integers in little-endian byte order in theoutput string. The low-order 32-bits of each integer are stored as a four-byte value at the cursor position withthe least significant byte stored first. For example,

    binary format i3 {3 -3 65536 1}

    will return a string equivalent to \x03\x00\x00\x00\xfd\xff\xff\xff\x00\x00\x01\x00I

    This form is the same as i except that it stores one or more one or more 32-bit integers in big-endian byteorder in the output string. For example,

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 28

  • binary format I3 {3 -3 65536 1}

    will return a string equivalent to \x00\x00\x00\x03\xff\xff\xff\xfd\x00\x01\x00\x00w

    This form is the same as c except that it stores one or more 64-bit integers in little-endian byte order in theoutput string. The low-order 64-bits of each integer are stored as an eight-byte value at the cursor positionwith the least significant byte stored first. For example,

    binary format w 7810179016327718216

    will return the string HelloTclW

    This form is the same as w except that it stores one or more one or more 64-bit integers in big-endian byteorder in the output string. For example,

    binary format Wc 4785469626960341345 110

    will return the string BigEndianf

    This form is the same as c except that it stores one or more one or more single-precision floating in themachine's native representation in the output string. This representation is not portable across architectures, soit should not be used to communicate floating point numbers across the network. The size of a floating pointnumber may vary across architectures, so the number of bytes that are generated may vary. If the valueoverflows the machine's native representation, then the value of FLT_MAX as defined by the system will beused instead. Because Tcl uses double-precision floating-point numbers internally, there may be some loss ofprecision in the conversion to single-precision. For example, on a Windows system running on an IntelPentium processor,

    binary format f2 {1.6 3.4}

    will return a string equivalent to \xcd\xcc\xcc\x3f\x9a\x99\x59\x40.d

    This form is the same as f except that it stores one or more one or more double-precision floating in themachine's native representation in the output string. For example, on a Windows system running on an IntelPentium processor,

    binary format d1 {1.6}

    will return a string equivalent to \x9a\x99\x99\x99\x99\x99\xf9\x3f.x

    Stores count null bytes in the output string. If count is not specified, stores one null byte. If count is *,generates an error. This type does not consume an argument. For example,

    binary format a3xa3x2a3 abc def ghi

    will return a string equivalent to abc\000def\000\000ghi.X

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 29

  • Moves the cursor back count bytes in the output string. If count is * or is larger than the current cursorposition, then the cursor is positioned at location 0 so that the next byte stored will be the first byte in theresult string. If count is omitted then the cursor is moved back one byte. This type does not consume anargument. For example,

    binary format a3X*a3X2a3 abc def ghi

    will return dghi.@

    Moves the cursor to the absolute location in the output string specified by count. Position 0 refers to the firstbyte in the output string. If count refers to a position beyond the last byte stored so far, then null bytes will beplaced in the uninitialized locations and the cursor will be placed at the specified location. If count is *, thenthe cursor is moved to the current end of the output string. If count is omitted, then an error will be generated.This type does not consume an argument. For example,

    binary format a5@2a1@*a3@10a1 abcde f ghi j

    will return abfdeghi\000\000j.

    BINARY SCAN

    The binary scan command parses fields from a binary string, returning the number of conversions performed. Stringgives the input to be parsed and formatString indicates how to parse it. Each varName gives the name of a variable;when a field is scanned from string the result is assigned to the corresponding variable.

    As with binary format, the formatString consists of a sequence of zero or more field specifiers separated by zero ormore spaces. Each field specifier is a single type character followed by an optional numeric count. Most fieldspecifiers consume one argument to obtain the variable into which the scanned values should be placed. The typecharacter specifies how the binary data is to be interpreted. The count typically indicates how many items of thespecified type are taken from the data. If present, the count is a non-negative decimal integer or *, which normallyindicates that all of the remaining items in the data are to be used. If there are not enough bytes left after the currentcursor position to satisfy the current field specifier, then the corresponding variable is left untouched and binary scanreturns immediately with the number of variables that were set. If there are not enough arguments for all of the fieldsin the format string that consume arguments, then an error is generated.

    A similar example as with binary format should explain the relation between field specifiers and arguments in caseof the binary scan subcommand:

    binary scan $bytes s3s first second

    This command (provided the binary string in the variable bytes is long enough) assigns a list of three integers to thevariable first and assigns a single value to the variable second. If bytes contains fewer than 8 bytes (i.e. four 2-byteintegers), no assignment to second will be made, and if bytes contains fewer than 6 bytes (i.e. three 2-byte integers),no assignment to first will be made. Hence:

    puts [binary scan abcdefg s3s first second]puts $first

    Tcl8.4.19/Tk8.4.19 Manual

    BINARY SCAN 30

  • puts $second

    will print (assuming neither variable is set previously):

    125185 25699 26213can't read "second": no such variable

    It is important to note that the c, s, and S (and i and I on 64bit systems) will be scanned into long data size values. Indoing this, values that have their high bit set (0x80 for chars, 0x8000 for shorts, 0x80000000 for ints), will be signextended. Thus the following will occur:

    set signShort [binary format s1 0x8000]binary scan $signShort s1 val; # val == 0xFFFF8000

    If you want to produce an unsigned value, then you can mask the return value to the desired size. For example, toproduce an unsigned short value:

    set val [expr {$val & 0xFFFF}]; # val == 0x8000

    Each type-count pair moves an imaginary cursor through the binary data, reading bytes from the current position. Thecursor is initially at position 0 at the beginning of the data. The type may be any one of the following characters:

    aThe data is a character string of length count. If count is *, then all of the remaining bytes in string will bescanned into the variable. If count is omitted, then one character will be scanned. All characters scanned willbe interpreted as being in the range \u0000-\u00ff so the encoding convertfrom command might be needed ifthe string is not an ISO 8859-1 string. For example,

    binary scan abcde\000fghi a6a10 var1 var2

    will return 1 with the string equivalent to abcde\000 stored in var1 and var2 left unmodified.A

    This form is the same as a, except trailing blanks and nulls are stripped from the scanned value before it isstored in the variable. For example,

    binary scan "abc efghi \000" A* var1

    will return 1 with abc efghi stored in var1.b

    The data is turned into a string of count binary digits in low-to-high order represented as a sequence of ``1''and ``0'' characters. The data bytes are scanned in first to last order with the bits being taken in low-to-highorder within each byte. Any extra bits in the last byte are ignored. If count is *, then all of the remaining bitsin string will be scanned. If count is omitted, then one bit will be scanned. For example,

    binary scan \x07\x87\x05 b5b* var1 var2

    will return 2 with 11100 stored in var1 and 1110000110100000 stored in var2.

    Tcl8.4.19/Tk8.4.19 Manual

    BINARY SCAN 31

  • BThis form is the same as b, except the bits are taken in high-to-low order within each byte. For example,

    binary scan \x70\x87\x05 B5B* var1 var2

    will return 2 with 01110 stored in var1 and 1000011100000101 stored in var2.h

    The data is turned into a string of count hexadecimal digits in low-to-high order represented as a sequence ofcharacters in the set ``0123456789abcdef''. The data bytes are scanned in first to last order with the hex digitsbeing taken in low-to-high order within each byte. Any extra bits in the last byte are ignored. If count is *,then all of the remaining hex digits in string will be scanned. If count is omitted, then one hex digit will bescanned. For example,

    binary scan \x07\x86\x05 h3h* var1 var2

    will return 2 with 706 stored in var1 and 50 stored in var2.H

    This form is the same as h, except the digits are taken in high-to-low order within each byte. For example,

    binary scan \x07\x86\x05 H3H* var1 var2

    will return 2 with 078 stored in var1 and 05 stored in var2.c

    The data is turned into count 8-bit signed integers and stored in the corresponding variable as a list. If count is*, then all of the remaining bytes in string will be scanned. If count is omitted, then one 8-bit integer will bescanned. For example,

    binary scan \x07\x86\x05 c2c* var1 var2

    will return 2 with 7 -122 stored in var1 and 5 stored in var2. Note that the integers returned are signed, butthey can be converted to unsigned 8-bit quantities using an expression like:

    expr { $num & 0xff }

    sThe data is interpreted as count 16-bit signed integers represented in little-endian byte order. The integers arestored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will bescanned. If count is omitted, then one 16-bit integer will be scanned. For example,

    binary scan \x05\x00\x07\x00\xf0\xff s2s* var1 var2

    will return 2 with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed, butthey can be converted to unsigned 16-bit quantities using an expression like:

    expr { $num & 0xffff }

    SThis form is the same as s except that the data is interpreted as count 16-bit signed integers represented inbig-endian byte order. For example,

    Tcl8.4.19/Tk8.4.19 Manual

    BINARY SCAN 32

  • binary scan \x00\x05\x00\x07\xff\xf0 S2S* var1 var2

    will return 2 with 5 7 stored in var1 and -16 stored in var2.i

    The data is interpreted as count 32-bit signed integers represented in little-endian byte order. The integers arestored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will bescanned. If count is omitted, then one 32-bit integer will be scanned. For example,

    binary scan \x05\x00\x00\x00\x07\x00\x00\x00\xf0\xff\xff\xff i2i* var1 var2

    will return 2 with 5 7 stored in var1 and -16 stored in var2. Note that the integers returned are signed, butthey can be converted to unsigned 32-bit quantities using an expression like:

    expr { $num & 0xffffffff }

    IThis form is the same as I except that the data is interpreted as count 32-bit signed integers represented inbig-endian byte order. For example,

    binary scan \x00\x00\x00\x05\x00\x00\x00\x07\xff\xff\xff\xf0 I2I* var1 var2

    will return 2 with 5 7 stored in var1 and -16 stored in var2.w

    The data is interpreted as count 64-bit signed integers represented in little-endian byte order. The integers arestored in the corresponding variable as a list. If count is *, then all of the remaining bytes in string will bescanned. If count is omitted, then one 64-bit integer will be scanned. For example,

    binary scan \x05\x00\x00\x00\x07\x00\x00\x00\xf0\xff\xff\xff wi* var1 var2

    will return 2 with 30064771077 stored in var1 and -16 stored in var2. Note that the integers returned aresigned and cannot be represented by Tcl as unsigned values.

    WThis form is the same as w except that the data is interpreted as count 64-bit signed integers represented inbig-endian byte order. For example,

    binary scan \x00\x00\x00\x05\x00\x00\x00\x07\xff\xff\xff\xf0 WI* var1 var2

    will return 2 with 21474836487 stored in var1 and -16 stored in var2.f

    The data is interpreted as count single-precision floating point numbers in the machine's native representation.The floating point numbers are stored in the corresponding variable as a list. If count is *, then all of theremaining bytes in string will be scanned. If count is omitted, then one single-precision floating point numberwill be scanned. The size of a floating point number may vary across architectures, so the number of bytesthat are scanned may vary. If the data does not represent a valid floating point number, the resulting value isundefined and compiler dependent. For example, on a Windows system running on an Intel Pentiumprocessor,

    binary scan \x3f\xcc\xcc\xcd f var1

    Tcl8.4.19/Tk8.4.19 Manual

    BINARY SCAN 33

  • will return 1 with 1.6000000238418579 stored in var1.d

    This form is the same as f except that the data is interpreted as count double-precision floating point numbersin the machine's native representation. For example, on a Windows system running on an Intel Pentiumprocessor,

    binary scan \x9a\x99\x99\x99\x99\x99\xf9\x3f d var1

    will return 1 with 1.6000000000000001 stored in var1.x

    Moves the cursor forward count bytes in string. If count is * or is larger than the number of bytes after thecurrent cursor cursor position, then the cursor is positioned after the last byte in string. If count is omitted,then the cursor is moved forward one byte. Note that this type does not consume an argument. For example,

    binary scan \x01\x02\x03\x04 x2H* var1

    will return 1 with 0304 stored in var1.X

    Moves the cursor back count bytes in string. If count is * or is larger than the current cursor position, then thecursor is positioned at location 0 so that the next byte scanned will be the first byte in string. If count isomitted then the cursor is moved back one byte. Note that this type does not consume an argument. Forexample,

    binary scan \x01\x02\x03\x04 c2XH* var1 var2

    will return 2 with 1 2 stored in var1 and 020304 stored in var2.@

    Moves the cursor to the absolute location in the data string specified by count. Note that position 0 refers tothe first byte in string. If count refers to a position beyond the end of string, then the cursor is positioned afterthe last byte. If count is omitted, then an error will be generated. For example,

    binary scan \x01\x02\x03\x04 c2@1H* var1 var2

    will return 2 with 1 2 stored in var1 and 020304 stored in var2.

    PLATFORM ISSUES

    Sometimes it is desirable to format or scan integer values in the native byte order for the machine. Refer to thebyteOrder element of the tcl_platform array to decide which type character to use when formatting or scanningintegers.

    EXAMPLES

    This is a procedure to write a Tcl string to a binary-encoded channel as UTF-8 data preceded by a length word:

    proc writeString {channel string} { set data [encoding convertto utf-8 $string]

    Tcl8.4.19/Tk8.4.19 Manual

    PLATFORM ISSUES 34

  • puts -nonewline [binary format Ia* \ [string length $data] $data]}

    This procedure reads a string from a channel that was written by the previously presented writeString procedure:

    proc readString {channel} { if {![binary scan [read $channel 4] I length]} { error "missing length" } set data [read $channel $length] return [encoding convertfrom utf-8 $data]}

    SEE ALSO

    format, scan, tclvars

    KEYWORDS

    binary, format, scan

    Copyright ' 1997 by Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 35

  • NAME

    break - Abort looping command

    SYNOPSIS

    break

    DESCRIPTION

    This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns aTCL_BREAK code, which causes a break exception to occur. The exception causes the current script to be abortedout to the innermost containing loop command, which then aborts its execution and returns normally. Breakexceptions are also handled in a few other situations, such as the catch command, Tk event bindings, and theoutermost scripts of procedure bodies.

    EXAMPLE

    Print a line for each of the integers from 0 to 5:

    for {set x 0} {$x 5} {

    break } puts "x is $x"}

    SEE ALSO

    catch, continue, for, foreach, return, while

    KEYWORDS

    abort, break, loop

    Copyright ' 1993-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 36

  • NAME

    catch - Evaluate script and trap exceptional returns

    SYNOPSIS

    catch script ?varName?

    DESCRIPTION

    The catch command may be used to prevent errors from aborting command interpretation. The catch command callsthe Tcl interpreter recursively to execute script, and always returns without raising an error, regardless of any errorsthat might occur while executing script.

    If script raises an error, catch will return a non-zero integer value corresponding to the exceptional return codereturned by evaluation of script. Tcl defines the normal return code from script evaluation to be zero (0), orTCL_OK. Tcl also defines four exceptional return codes: 1 (TCL_ERROR), 2 (TCL_RETURN), 3(TCL_BREAK), and 4 (TCL_CONTINUE). Errors during evaluation of a script are indicated by a return code ofTCL_ERROR. The other exceptional return codes are returned by the return, break, and continue commands and inother special situations as documented. Tcl packages can define new commands that return other integer values asreturn codes as well, and scripts that make use of the return -code command can also have return codes other than thefive defined by Tcl.

    If the varName argument is given, then the variable it names is set to the result of the script evaluation. When thereturn code from the script is 1 (TCL_ERROR), the value stored in varName is an error message. When the returncode from the script is 0 (TCL_OK), the value stored in resultVarName is the value returned from script.

    If script does not raise an error, catch will return 0 (TCL_OK) and set the variable to the value returned from script.

    Note that catch catches all exceptions, including those generated by break and continue as well as errors. The onlyerrors that are not caught are syntax errors found when the script is compiled. This is because the catch command onlycatches errors during runtime. When the catch statement is compiled, the script is compiled as well and any syntaxerrors will generate a Tcl error.

    EXAMPLES

    The catch command may be used in an if to branch based on the success of a script.

    if { [catch {open $someFile w} fid] } { puts stderr "Could not open $someFile for writing\n$fid" exit 1}

    The catch command will not catch compiled syntax errors. The first time proc foo is called, the body will be compiledand a Tcl error will be generated.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 37

  • proc foo {} {catch {expr {1 +- }}

    }

    SEE ALSO

    break, continue, error, return, tclvars

    KEYWORDS

    catch, error

    Copyright ' 1993-1994 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 38

  • NAME

    cd - Change working directory

    SYNOPSIS

    cd ?dirName?

    DESCRIPTION

    Change the current working directory to dirName, or to the home directory (as specified in the HOME environmentvariable) if dirName is not given. Returns an empty string. Note that the current working directory is a per-processresource; the cd command changes the working directory for all interpreters and (in a threaded environment) allthreads.

    EXAMPLES

    Change to the home directory of the user fred:

    cd ~fred

    Change to the directory lib that is a sibling directory of the current one:

    cd ../lib

    SEE ALSO

    filename, glob, pwd

    KEYWORDS

    working directory

    Copyright ' 1993 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 39

  • NAME

    clock - Obtain and manipulate timeSYNOPSIS

    clock option ?arg arg ...?DESCRIPTION

    clock clicks ?-milliseconds?clock format clockValue ?-format string? ?-gmt boolean?

    %%%a%A%b%B%c%C%d%D%e%g%G%h%H%I%j%k%l%m%M%n%p%r%R%s%S%t%T%u%U%V%w%W%x%X%y%Y%Z

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 40

  • clock scan dateString ?-base clockVal? ?-gmt boolean?timedateISO 8601 point-in-timerelative time

    clock secondsSEE ALSOKEYWORDS

    NAME

    clock - Obtain and manipulate time

    SYNOPSIS

    clock option ?arg arg ...?

    DESCRIPTION

    This command performs one of several operations that may obtain or manipulate strings or values that represent somenotion of time. The option argument determines what action is carried out by the command. The legal options (whichmay be abbreviated) are:

    clock clicks ?-milliseconds?Return a high-resolution time value as a system-dependent integer value. The unit of the value issystem-dependent but should be the highest resolution clock available on the system such as a CPU cyclecounter. If -milliseconds is specified, then the value is guaranteed to be of millisecond granularity. This valueshould only be used for the relative measurement of elapsed time.

    clock format clockValue ?-format string? ?-gmt boolean?Converts an integer time value, typically returned by clock seconds, clock scan, or the atime or mtimeoptions of the file command, to human-readable form. If the -format argument is present the next argument isa string that describes how the date and time are to be formatted. Field descriptors consist of a % followed bya field descriptor character. All other characters are copied into the result. Valid field descriptors are:

    %%Insert a %.

    %aAbbreviated weekday name (Mon, Tue, etc.).

    %AFull weekday name (Monday, Tuesday, etc.).

    %bAbbreviated month name (Jan, Feb, etc.).

    %BFull month name.

    %c

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 41

  • Locale specific date and time. The format for date and time in the default "C" locale on Unix/Mac is"%a %b %d %H:%M:%S %Y". On Windows, this value is the locale specific long date and time, asspecified in the Regional Options control panel settings.

    %CFirst two digits of the four-digit year (19 or 20).

    %dDay of month (01 - 31).

    %DDate as %m/%d/%y.

    %eDay of month (1 - 31), no leading zeros.

    %gThe ISO8601 year number corresponding to the ISO8601 week (%V), expressed as a two-digityear-of-the-century, with leading zero if necessary.

    %GThe ISO8601 year number corresponding to the ISO8601 week (%V), expressed as a four-digitnumber.

    %hAbbreviated month name.

    %HHour in 24-hour format (00 - 23).

    %IHour in 12-hour format (01 - 12).

    %jDay of year (001 - 366).

    %kHour in 24-hour format, without leading zeros (0 - 23).

    %lHour in 12-hour format, without leading zeros (1 - 12).

    %mMonth number (01 - 12).

    %MMinute (00 - 59).

    %nInsert a newline.

    %pAM/PM indicator.

    %rTime in a locale-specific "meridian" format. The "meridian" format in the default "C" locale is"%I:%M:%S %p".

    %RTime as %H:%M.

    %sCount of seconds since the epoch, expressed as a decimal integer.

    %SSeconds (00 - 59).

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 42

  • %tInsert a tab.

    %TTime as %H:%M:%S.

    %uWeekday number (Monday = 1, Sunday = 7).

    %UWeek of year (00 - 52), Sunday is the first day of the week.

    %VWeek of year according to ISO-8601 rules. Week 1 of a given year is the week containing 4 January.

    %wWeekday number (Sunday = 0, Saturday = 6).

    %WWeek of year (00 - 52), Monday is the first day of the week.

    %xLocale specific date format. The format for a date in the default "C" locale for Unix/Mac is"%m/%d/%y". On Windows, this value is the locale specific short date format, as specified in theRegional Options control panel settings.

    %XLocale specific 24-hour time format. The format for a 24-hour time in the default "C" locale forUnix/Mac is "%H:%M:%S". On Windows, this value is the locale specific time format, as specified inthe Regional Options control panel settings.

    %yYear without century (00 - 99).

    %YYear with century (e.g. 1990)

    %ZTime zone name.

    If the -format argument is not specified, the format string "%a %b %d %H:%M:%S %Z %Y" is used. Ifthe -gmt argument is present the next argument must be a boolean which if true specifies that the time will beformatted as Greenwich Mean Time. If false then the local timezone will be used as defined by the operatingenvironment.

    clock scan dateString ?-base clockVal? ?-gmt boolean?Convert dateString to an integer clock value (see clock seconds). This command can parse and convertvirtually any standard date and/or time string, which can include standard time zone mnemonics. If only atime is specified, the current date is assumed. If the string does not contain a time zone mnemonic, the localtime zone is assumed, unless the -gmt argument is true, in which case the clock value is calculated assumingthat the specified time is relative to Greenwich Mean Time. -gmt, if specified, affects only the computed timevalue; it does not impact the interpretation of -base.

    If the -base flag is specified, the next argument should contain an integer clock value. Only the date in thisvalue is used, not the time. This is useful for determining the time on a specific day or doing otherdate-relative conversions.

    The dateString consists of zero or more specifications of the following form:

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 43

  • timeA time of day, which is of the form: hh?:mm?:ss?? ?meridian? ?zone? or hhmm ?meridian? ?zone?. Ifno meridian is specified, hh is interpreted on a 24-hour clock.

    dateA specific month and day with optional year. The acceptable formats are mm/dd?/yy?, monthname dd?, yy?, dd monthname ?yy?, day, dd monthname yy, ?CC?yymmdd, ?CC?yy-mm-dd,dd-monthname-?CC?yy. The default year is the current year. If the year is less than 100, we treat theyears 00-68 as 2000-2068 and the years 69-99 as 1969-1999. Not all platforms can represent the years38-70, so an error may result if these years are used.

    ISO 8601 point-in-timeAn ISO 8601 point-in-time specification, such as CCyymmddThhmmss, where T is the literal T,CCyymmdd hhmmss, or CCyymmddThh:mm:ss. Note that only these three formats are accepted. Thecommand does not accept the full range of point-in-time specifications specified in ISO8601. Otherformats can be recognized by using commands such as regexp to extract their fields and reorganizethem into a form accepted by the clock scan command.

    relative timeA specification relative to the current time. The format is number unit acceptable units are year,fortnight, month, week, day, hour, minute (or min), and second (or sec). The unit can be specifiedas a singular or plural, as in 3 weeks. These modifiers may also be specified: tomorrow, yesterday,today, now, last, this, next, ago.

    The actual date is calculated according to the following steps. First, any absolute date and/or time isprocessed and converted. Using that time as the base, day-of-week specifications are added. Next,relative specifications are used. If a date or day is specified, and no absolute or relative time is given,midnight is used. Finally, a correction is applied so that the correct hour of the day is produced afterallowing for daylight savings time differences and the correct date is given when going from the endof a long month to a short month.

    Daylight savings time correction is applied only when the relative time is specified in units of days ormore, ie, days, weeks, fortnights, months or years. This means that when crossing the daylight savingstime boundary, different results will be given for clock scan "1 day" and clock scan "24 hours":

    % clock scan "1 day" -base [clock scan 1999-10-31]941443200% clock scan "24 hours" -base [clock scan 1999-10-31]941439600

    clock secondsReturn the current date and time as a system-dependent integer value. The unit of the value is seconds,allowing it to be used for relative time calculations. The value is usually defined as total elapsed time from an``epoch''. You shouldn't assume the value of the epoch.

    SEE ALSO

    date, time

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 44

  • KEYWORDS

    clock, date, time

    Copyright ' 1992-1995 Karl Lehenbauer and Mark Diekhans.Copyright ' 1995-1997 Sun Microsystems, Inc.Copyright ' 1998-1999 Scriptics CorporationCopyright ' 2002 ActiveState CorporationCopyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    KEYWORDS 45

  • NAME

    close - Close an open channel.

    SYNOPSIS

    close channelId

    DESCRIPTION

    Closes the channel given by channelId.

    ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), thereturn value from an invocation of open or socket, or the result of a channel creation command provided by a Tclextension.

    All buffered output is flushed to the channel's output device, any buffered input is discarded, the underlying file ordevice is closed, and channelId becomes unavailable for use.

    If the channel is blocking, the command does not return until all output is flushed. If the channel is nonblocking andthere is unflushed output, the channel remains open and the command returns immediately; output will be flushed inthe background and the channel will be closed when all the flushing is complete.

    If channelId is a blocking channel for a command pipeline then close waits for the child processes to complete.

    If the channel is shared between interpreters, then close makes channelId unavailable in the invoking interpreter buthas no other effect until all of the sharing interpreters have closed the channel. When the last interpreter in which thechannel is registered invokes close, the cleanup actions described above occur. See the interp command for adescription of channel sharing.

    Channels are automatically closed when an interpreter is destroyed and when the process exits. Channels are switchedto blocking mode, to ensure that all output is correctly flushed before the process exits.

    The command returns an empty string, and may generate an error if an error occurs while flushing output. If acommand in a command pipeline created with open returns an error, close generates an error (similar to the execcommand.)

    EXAMPLE

    This illustrates how you can use Tcl to ensure that files get closed even when errors happen by combining catch, closeand return:

    proc withOpenFile {filename channelVar script} { upvar 1 $channelVar chan set chan [open $filename] catch {

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 46

  • uplevel 1 $script } result options

    close $chan return -options $options $result}

    SEE ALSO

    file, open, socket, eof, Tcl_StandardChannels

    KEYWORDS

    blocking, channel, close, nonblocking

    Copyright ' 1993 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    SEE ALSO 47

  • NAME

    concat - Join lists together

    SYNOPSIS

    concat ?arg arg ...?

    DESCRIPTION

    This command joins each of its arguments together with spaces after trimming leading and trailing white-space fromeach of them. If all the arguments are lists, this has the same effect as concatenating them into a single list. It permitsany number of arguments; if no args are supplied, the result is an empty string.

    EXAMPLES

    Although concat will concatenate lists (so the command:

    concat a b {c d e} {f {g h}}

    will return "a b c d e f {g h}" as its result), it will also concatenate things that are not lists, and hence the command:

    concat " a b {c " d " e} f"

    will return "a b {c d e} f" as its result.

    Note that the concatenation does not remove spaces from the middle of its arguments, so the command:

    concat "a b c" { d e f }

    will return "a b c d e f" (i.e. with three spaces between the a, the b and the c).

    SEE ALSO

    append, eval

    KEYWORDS

    concatenate, join, lists

    Copyright ' 1993 The Regents of the University of California.Copyright ' 1994-1996 Sun Microsystems, Inc.Copyright ' 1995-1997 Roger E. Critchlow Jr.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 48

  • NAME

    continue - Skip to the next iteration of a loop

    SYNOPSIS

    continue

    DESCRIPTION

    This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns aTCL_CONTINUE code, which causes a continue exception to occur. The exception causes the current script to beaborted out to the innermost containing loop command, which then continues with the next iteration of the loop. Catchexceptions are also handled in a few other situations, such as the catch command and the outermost scripts ofprocedure bodies.

    EXAMPLE

    Print a line for each of the integers from 0 to 10 except 5:

    for {set x 0} {$x

  • NAME

    dde - Execute a Dynamic Data Exchange commandSYNOPSIS

    package require dde 1.2dde eval ?-async? service cmd ?arg ...?dde execute ?-async? service topic datadde poke service topic item datadde request ?-binary? service topic datadde servername ?topic?dde services service topic

    DESCRIPTIONDDE COMMANDS

    dde servername ?topic?dde execute ?-async? service topic datadde poke service topic item datadde request ?-binary? service topic itemdde services service topicdde eval ?-async? topic cmd ?arg arg ...?

    DDE AND TCLEXAMPLESEE ALSOKEYWORDS

    NAME

    dde - Execute a Dynamic Data Exchange command

    SYNOPSIS

    package require dde 1.2dde eval ?-async? service cmd ?arg ...?dde execute ?-async? service topic datadde poke service topic item datadde request ?-binary? service topic datadde servername ?topic?dde services service topic

    DESCRIPTION

    This command allows an application to send Dynamic Data Exchange (DDE) command when running underMicrosoft Windows. Dynamic Data Exchange is a mechanism where applications can exchange raw data. Each DDEtransaction needs a service name and a topic. Both the service name and topic are application defined; Tcl uses theservice name TclEval, while the topic name is the name of the interpreter given by dde servername. Otherapplications have their own service names and topics. For instance, Microsoft Excel has the service name Excel.

    Tcl8.4.19/Tk8.4.19 Manual

    NAME 50

  • The eval and execute commands accept the option -async:

    DDE COMMANDS

    The following commands are a subset of the full Dynamic Data Exchange set of commands.

    dde servername ?topic?dde servername registers the interpreter as a DDE server with the service name TclEval and the topic namespecified by topic. If no topic is given, dde servername returns the name of the current topic or the emptystring if it is not registered as a service.

    dde execute ?-async? service topic datadde execute takes the data and sends it to the server indicated by service with the topic indicated by topic.Typically, service is the name of an application, and topic is a file to work on. The data field is given to theremote application. Typically, the application treats the data field as a script, and the script is run in theapplication. The -async option requests asynchronous invocation. The command returns an error message ifthe script did not run, unless the -async flag was used, in which case the command returns immediately withno error.

    dde poke service topic item datadde poke passes the data to the server indicated by service using the topic and item specified. Typically,service is the name of an application. topic is application specific but can be a command to the server or thename of a file to work on. The item is also application specific and is often not used, but it must always benon-null. The data field is given to the remote application.

    dde request ?-binary? service topic itemdde request is typically used to get the value of something; the value of a cell in Microsoft Excel or the textof a selection in Microsoft Word. service is typically the name of an application, topic is typically the name ofthe file, and item is application-specific. The command returns the value of item as defined in the application.Normally this is interpreted to be a string with terminating null. If -binary is specified, the result is returnedas a byte array.

    dde services service topicdde services returns a list of service-topic pairs that currently exist on the machine. If service and topic areboth null strings ({}), then all service-topic pairs currently available on the system are returned. If service isnull and topic is not, then all services with the specified topic are returned. If service is not null and topic is,all topics for a given service are returned. If both are not null, if that service-topic pair currently exists, it isreturned; otherwise, null is returned.

    dde eval ?-async? topic cmd ?arg arg ...?dde eval evaluates a command and its arguments using the interpreter specified by topic. The DDE servicemust be the TclEval service. The -async option requests asynchronous invocation. The command returns anerror message if the script did not run, unless the -async flag was used, in which case the command returnsimmediately with no error. This command can be used to replace send on Windows.

    DDE AND TCL

    A Tcl interpreter always has a service name of TclEval. Each different interpreter of all running Tcl applications mustbe given a unique name specified by dde servername. Each interp is available as a DDE topic only if the ddeservername command was used to set the name of the topic for each interp. So a dde services TclEval {} commandwill return a list of service-topic pairs, where each of the currently running interps will be a topic.

    Tcl8.4.19/Tk8.4.19 Manual

    DDE COMMANDS 51

  • When Tcl processes a dde execute command, the data for the execute is run as a script in the interp named by thetopic of the dde execute command.

    When Tcl processes a dde request command, it returns the value of the variable given in the dde command in thecontext of the interp na