::xowiki::Page create ::xowiki::page2 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
after ms ?script script script ...?
after cancel id
after cancel script script script ...
after idle ?script script script ...?
after info ?id?
This command is used to delay execution of the program or to execute a command in background sometime in the future. It has several forms, depending on the first argument to the command:
The after ms and after idle forms of the command assume that the application is event driven: the delayed commands will 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.
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 that the event loop is not starved
by the rescheduling of processing steps (arranging for the next step to
be done using an already-triggered timer event only when the event queue
has been drained) and is useful when you want to ensure that a Tk GUI remains
responsive during a slow task. proc doOneStep {} {
if {[::my_calc::one_step]} {
after idle [list after 0 doOneStep]
}
}
doOneStep
} text/html} \ -set mime_type text/html \ -set title en:after.n \ -set lang en ::xowiki::Page create ::xowiki::page3 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
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. The result of this command is the new value stored in variable 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.
set var 0
for {set i 1} {$i<=10} {incr i} {
append var "," $i
}
puts $var
# Prints 0,1,2,3,4,5,6,7,8,9,10
} text/html} \ -set mime_type text/html \ -set title en:append.n \ -set lang en ::xowiki::Page create ::xowiki::page4 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command performs one of several operations on the variable given by arrayName. Unless otherwise specified for individual commands below, arrayName must be the name of an existing array variable. The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:
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
} text/html} \ -set mime_type text/html \ -set title en:array.n \ -set lang en ::xowiki::Page create ::xowiki::page5 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_execok.n \ -set lang en ::xowiki::Page create ::xowiki::page6 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]} text/html} \ -set mime_type text/html \ -set title en:bgerror.n \ -set lang en ::xowiki::Page create ::xowiki::page13 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_import.n \ -set lang en ::xowiki::Page create ::xowiki::page7 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_load.n \ -set lang en ::xowiki::Page create ::xowiki::page8 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_mkindex.n \ -set lang en ::xowiki::Page create ::xowiki::page9 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_mkindex_old.n \ -set lang en ::xowiki::Page create ::xowiki::page10 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_qualify.n \ -set lang en ::xowiki::Page create ::xowiki::page11 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:auto_reset.n \ -set lang en ::xowiki::Page create ::xowiki::page12 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
bgerror - Command invoked to process background errorsSynopsis
bgerror message
Description
The bgerror command doesn’t exist as built-in part of Tcl. Instead, individual applications or users can define a bgerror 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 the application. For example, if an error occurs while executing a command specified with the after command, then it is a background error. For a non-background error, the error can simply be returned up through nested Tcl command evaluations until it reaches the top-level code in the application; then the application can report the error in whatever way it wishes. When a background error occurs, the unwinding ends in the Tcl library and there is no obvious way for Tcl to report the error.
When Tcl detects a background error, it saves information about the error and invokes the bgerror command later as an idle event handler. Before invoking bgerror, Tcl restores the errorInfo and errorCode variables to their values at the time the error occurred, then it invokes bgerror with the error message as its only argument. Tcl assumes that the application has implemented the bgerror command, and that the command will report the error in a way that makes sense 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 been defined) 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 for each error, in the order they occurred. However, if bgerror returns with a break exception, then any remaining errors are skipped without calling bgerror.
Tcl has no default implementation for bgerror. However, in applications using Tk there is a default bgerror procedure which posts a dialog box containing the error message and offers the user a chance to see a stack trace showing where the error occurred. In addition to allowing the user to view the stack trace, the dialog provides an additional application configurable button which may be used, for example, to save the stack trace to a file. By default, this is the behavior associated with that button. This behavior can be redefined by setting the option database values *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 the command when it is evaluated. If either of these options is set to the empty string, then the additional button will not be 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 avoiding bgerror. The reason for this is that the application programmer may also want to define a bgerror, or use other code 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
[[en:after.n]] , [[en:tclvars.n]]
Keywords
background error, reporting
This command provides facilities for manipulating binary data. The first form, binary format, creates a binary string from normal Tcl values. For example, given the values 16 and 22, on a 32 bit architecture, it might produce an 8-byte binary string consisting of two 4-byte integers, one for each of the numbers. The second form of the command, binary scan, does the opposite: it extracts data from a binary string and returns it as ordinary Tcl string values.
The binary format command generates a binary string whose layout is specified by the formatString and whose contents 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 field specifier is a single type character followed by an optional numeric count. Most field specifiers consume one argument to obtain the value to be formatted. The type character specifies how the value is to be formatted. The count typically indicates how many items of the specified type are taken from the value. If present, the count is a non-negative decimal integer or *, which normally indicates that all of the items in the value are to be used. If the number of arguments does not match the number of fields in the format string that consume arguments, then an error is 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 the first three will be used.
The second argument is associated with the second field specifier. The resulting
binary string contains 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 and advancing 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:
binary format a7a*a alpha bravo charlie
will return a string equivalent to alpha\000\000bravoc.
binary format A6A*A alpha bravo charlie
will return alpha bravoc.
binary format b5b* 11100 111000011010
will return a string equivalent to \x07\x87\x05.
binary format B5B* 11100 111000011010
will return a string equivalent to \xe0\xe1\xa0.
binary format h3h* AB def
will return a string equivalent to \xba\x00\xed\x0f.
binary format H3H* ab DEF
will return a string equivalent to \xab\x00\xde\xf0.
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.
binary format s3 {3 -3 258 1}
will return a string equivalent to \x03\x00\xfd\xff\x02\x01.
binary format S3 {3 -3 258 1}
will return a string equivalent to \x00\x03\xff\xfd\x01\x02.
binary format i3 {3 -3 65536 1}
will return a string equivalent to
binary format I3 {3 -3 65536 1}
will return a string equivalent to
binary format w 7810179016327718216
binary format Wc 4785469626960341345 110
binary format f2 {1.6 3.4}
will return a string equivalent to \xcd\xcc\xcc\x3f\x9a\x99\x59\x40.
binary format d1 {1.6}
will return a string equivalent to \x9a\x99\x99\x99\x99\x99\xf9\x3f.
binary format a3xa3x2a3 abc def ghi
will return a string equivalent to abc\000def\000\000ghi.
binary format a3X*a3X2a3 abc def ghi
will return dghi.
binary format a5@2a1@*a3@10a1 abcde f ghi j
will return abfdeghi\000\000j.
The binary scan command parses fields from a binary string, returning the number of conversions performed. String gives 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 or more spaces. Each field specifier is a single type character followed by an optional numeric count. Most field specifiers consume one argument to obtain the variable into which the scanned values should be placed. The type character specifies how the binary data is to be interpreted. The count typically indicates how many items of the specified type are taken from the data. If present, the count is a non-negative decimal integer or *, which normally indicates that all of the remaining items in the data are to be used. If there are not enough bytes left after the current cursor position to satisfy the current field specifier, then the corresponding variable is left untouched and binary scan returns immediately with the number of variables that were set. If there are not enough arguments for all of the fields in 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 case of 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 the variable first and assigns
a single value to the variable second. If bytes contains fewer than 8 bytes
(i.e. four 2-byte integers), 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]
will print (assuming neither variable is set previously):
puts $first
puts $second
1
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. In doing this, values that
have their high bit set (0x80 for chars, 0x8000 for shorts, 0x80000000
for ints), will be sign extended. Thus the following will occur:
25185 25699 26213
can’t read "second": no such variable
set signShort [binary format s1 0x8000]
If you want to produce an unsigned value, then you can mask the return
value to the desired size. For example, to produce an unsigned short
value:
binary scan $signShort s1 val; # val == 0xFFFF8000
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. The cursor is initially at position
0 at the beginning of the data. The type may be any one of the following
characters:
binary scan abcde\000fghi a6a10 var1 var2
will return 1 with the string equivalent to abcde\000 stored in var1 and var2 left unmodified.
binary scan "abc efghi \000" A* var1
will return 1 with abc efghi stored in var1.
binary scan \x07\x87\x05 b5b* var1 var2
will return 2 with 11100 stored in var1 and 1110000110100000 stored in var2.
binary scan \x70\x87\x05 B5B* var1 var2
will return 2 with 01110 stored in var1 and 1000011100000101 stored in var2.
binary scan \x07\x86\x05 h3h* var1 var2
will return 2 with 706 stored in var1 and 50 stored in var2.
binary scan \x07\x86\x05 H3H* var1 var2
will return 2 with 078 stored in var1 and 05 stored in var2.
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, but they can be converted to unsigned 8-bit quantities using an expression like:
expr { $num & 0xff }
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, but they can be converted to unsigned 16-bit quantities using an expression like:
expr { $num & 0xffff }
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.
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, but they can be converted to unsigned 32-bit quantities using an expression like:
expr { $num & 0xffffffff }
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.
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 are signed and cannot be represented by Tcl as unsigned values.
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.
binary scan \x3f\xcc\xcc\xcd f var1
will return 1 with 1.6000000238418579 stored in var1.
binary scan \x9a\x99\x99\x99\x99\x99\xf9\x3f d var1
will return 1 with 1.6000000000000001 stored in var1.
binary scan \x01\x02\x03\x04 x2H* var1
will return 1 with 0304 stored in var1.
binary scan \x01\x02\x03\x04 c2XH* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2.
binary scan \x01\x02\x03\x04 c2@1H* var1 var2
will return 2 with 1 2 stored in var1 and 020304 stored in var2.
proc writeString {channel string} {
set data [encoding convertto utf-8 $string]
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]
}
} text/html} \ -set mime_type text/html \ -set title en:binary.n \ -set lang en ::xowiki::Page create ::xowiki::page14 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns a TCL_BREAK code, which causes a break exception to occur. The exception causes the current script to be aborted out to the innermost containing loop command, which then aborts its execution and returns normally. Break exceptions are also handled in a few other situations, such as the catch command, Tk event bindings, and the outermost scripts of procedure bodies.
for {set x 0} {$x<10} {incr x} {
if {$x > 5} {
break
}
puts "x is $x"
}
} text/html} \ -set mime_type text/html \ -set title en:break.n \ -set lang en ::xowiki::Page create ::xowiki::page15 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
case string ?in? {patList body ?patList body ...?}
Note: the case command is obsolete and is supported only for backward compatibility. At some point in the future it may be removed entirely. You should use the switch command instead.
The case command matches string against each of the patList arguments in order. Each patList argument is a list of one or more patterns. If any of these patterns matches string then case evaluates the following body argument by passing it recursively to the Tcl interpreter and returns the result of that evaluation. Each patList argument consists of a single pattern or list of patterns. Each pattern may contain any of the wild-cards described under string match. If a patList argument is default, the corresponding body will be evaluated if no patList matches string. If no patList argument matches string and no default is given, then the case command returns an empty string.
Two syntaxes are provided for the patList and body arguments. The first uses a separate argument for each of the patterns and commands; this form is convenient if substitutions are desired on some of the patterns or commands. The second form places all of the patterns and commands together into a single argument; the argument must have proper list structure, with the elements of the list being the patterns and commands. The second form makes it easy to construct multi-line case commands, since the braces around the whole list make it unnecessary to include a backslash at the end of each line. Since the patList arguments are in braces in the second form, no command or variable substitutions are performed on them; this makes the behavior of the second form different than the first form in some cases.
} text/html} \ -set mime_type text/html \ -set title en:case.n \ -set lang en ::xowiki::Page create ::xowiki::page16 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The catch command may be used to prevent errors from aborting command interpretation. The catch command calls the Tcl interpreter recursively to execute script, and always returns without raising an error, regardless of any errors that might occur while executing script.
If script raises an error, catch will return a non-zero integer value corresponding to the exceptional return code returned by evaluation of script. Tcl defines the normal return code from script evaluation to be zero (0), or TCL_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 of TCL_ERROR. The other exceptional return codes are returned by the return, break, and continue commands and in other special situations as documented. Tcl packages can define new commands that return other integer values as return codes as well, and scripts that make use of the return -code command can also have return codes other than the five defined by Tcl.
If the varName argument is given, then the variable it names is set to the result of the script evaluation. When the return code from the script is 1 (TCL_ERROR), the value stored in varName is an error message. When the return code 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 only errors that are not caught are syntax errors found when the script is compiled. This is because the catch command only catches errors during runtime. When the catch statement is compiled, the script is compiled as well and any syntax errors will generate a Tcl error.
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 compiled and a Tcl error will be generated.
proc foo {} {
catch {expr {1 +- }}
}
} text/html} \ -set mime_type text/html \ -set title en:catch.n \ -set lang en ::xowiki::Page create ::xowiki::page17 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Change the current working directory to dirName, or to the home directory (as specified in the HOME environment variable) if dirName is not given. Returns an empty string. Note that the current working directory is a per-process resource; the cd command changes the working directory for all interpreters and (in a threaded environment) all threads.
cd ~fred
Change to the directory lib that is a sibling directory of the current
one: cd ../lib
} text/html} \ -set mime_type text/html \ -set title en:cd.n \ -set lang en ::xowiki::Page create ::xowiki::page18 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command performs one of several operations that may obtain or manipulate strings or values that represent some notion of time. The option argument determines what action is carried out by the command. The legal options (which may be abbreviated) are:
If the -format argument is not specified, the format string "%a %b %d %H:%M:%S %Z %Y" is used. If the -gmt argument is present the next argument must be a boolean which if true specifies that the time will be formatted as Greenwich Mean Time. If false then the local timezone will be used as defined by the operating environment.
If the -base flag is specified, the next argument should contain an integer clock value. Only the date in this value is used, not the time. This is useful for determining the time on a specific day or doing other date-relative conversions.
The dateString consists of zero or more specifications of the following form:
The actual date is calculated according to the following steps. First, any absolute date and/or time is processed 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 after allowing for daylight savings time differences and the correct date is given when going from the end of a long month to a short month.Daylight savings time correction is applied only when the relative time is specified in units of days or more, ie, days, weeks, fortnights, months or years. This means that when crossing the daylight savings time 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
} text/html} \ -set mime_type text/html \ -set title en:clock.n \ -set lang en ::xowiki::Page create ::xowiki::page19 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
channelId
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), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
All buffered output is flushed to the channel’s output device, any buffered input is discarded, the underlying file or device 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 and there is unflushed output, the channel remains open and the command returns immediately; output will be flushed in the 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 but has no other effect until all of the sharing interpreters have closed the channel. When the last interpreter in which the channel is registered invokes close, the cleanup actions described above occur. See the interp command for a description of channel sharing.
Channels are automatically closed when an interpreter is destroyed and when the process exits. Channels are switched to 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 a command in a command pipeline created with open returns an error, close generates an error (similar to the exec command.)
proc withOpenFile {filename channelVar script} {
upvar 1 $channelVar chan
set chan [open $filename]
catch {
uplevel 1 $script
} result options
close $chan
return -options $options $result
}
} text/html} \ -set mime_type text/html \ -set title en:close.n \ -set lang en ::xowiki::Page create ::xowiki::page20 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command joins each of its arguments together with spaces after trimming leading and trailing white-space from each of them. If all the arguments are lists, this has the same effect as concatenating them into a single list. It permits any number of arguments; if no args are supplied, the result is an empty string.
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).
} text/html} \ -set mime_type text/html \ -set title en:concat.n \ -set lang en ::xowiki::Page create ::xowiki::page21 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command is typically invoked inside the body of a looping command such as for or foreach or while. It returns a TCL_CONTINUE code, which causes a continue exception to occur. The exception causes the current script to be aborted out to the innermost containing loop command, which then continues with the next iteration of the loop. Catch exceptions are also handled in a few other situations, such as the catch command and the outermost scripts of procedure bodies.
for {set x 0} {$x<10} {incr x} {
if {$x == 5} {
continue
}
puts "x is $x"
}
} text/html} \ -set mime_type text/html \ -set title en:continue.n \ -set lang en ::xowiki::Page create ::xowiki::page22 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
package require dde 1.2
dde eval ?-async? service cmd ?arg ...?
dde execute ?-async? service topic data
dde poke service topic item data
dde request ?-binary? service topic data
dde servername ?topic?
dde services
service topic
This command allows an application to send Dynamic Data Exchange (DDE) command when running under Microsoft Windows. Dynamic Data Exchange is a mechanism where applications can exchange raw data. Each DDE transaction needs a service name and a topic. Both the service name and topic are application defined; Tcl uses the service name TclEval, while the topic name is the name of the interpreter given by dde servername. Other applications have their own service names and topics. For instance, Microsoft Excel has the service name Excel.
The eval and execute commands accept the option -async:
The following commands are a subset of the full Dynamic Data Exchange set of commands.
When Tcl processes a dde execute command, the data for the execute is run as a script in the interp named by the topic 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 the context of the interp named by the dde topic. Tcl reserves the variable $TCLEVAL$EXECUTE$RESULT for internal use, and dde request commands for that variable will give unpredictable results.
An external application which wishes to run a script in Tcl should have that script store its result in a variable, run the dde execute command, and the run dde request to get the value of the variable.
When using DDE, be careful to ensure that the event queue is flushed using either update or vwait. This happens by default when using wish unless a blocking command is called (such as exec without adding the & to place the process in the background). If for any reason the event queue is not flushed, DDE commands may hang until the event queue is flushed. This can create a deadlock situation.
package require dde
dde execute iexplore WWW_OpenURL http://www.tcl.tk/
} text/html} \ -set mime_type text/html \ -set title en:dde.n \ -set lang en ::xowiki::Page create ::xowiki::page23 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Strings in Tcl are encoded using 16-bit Unicode characters. Different operating system interfaces or applications may generate strings in other encodings such as Shift-JIS. The encoding command helps to bridge the gap between Unicode and these other formats.
Performs one of several encoding related operations, depending on option. The legal options are:
It is common practice to write script files
using a text editor that produces output in the euc-jp encoding, which represents
the ASCII characters as singe bytes and Japanese characters as two bytes.
This makes it easy to embed literal strings that correspond to non-ASCII
characters by simply typing the strings in place in the script. However,
because the source command always reads files using the current system
encoding, Tcl will only source such files correctly when the encoding used
to write the file is the same. This tends not to be true in an internationalized
setting. For example, if such a file was sourced in North America (where
the ISO8859-1 is normally used), each byte in the file would be treated
as a separate character that maps to the 00 page in Unicode. The resulting
Tcl strings will not contain the expected Japanese characters. Instead,
they will contain a sequence of Latin-1 characters that correspond to the
bytes of the original string. The encoding command can be used to convert
this string to the expected Japanese Unicode characters. For example,
set s [encoding convertfrom euc-jp "\xA4\xCF"]
would return the Unicode string "\u306F", which is the Hiragana letter HA.
} text/html} \ -set mime_type text/html \ -set title en:encoding.n \ -set lang en ::xowiki::Page create ::xowiki::page24 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Returns 1 if an end of file condition occurred during the most recent input operation on channelId (such as gets), 0 otherwise.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
set f [open somefile.txt]
while {1} {
set line [gets $f]
if {[eof $f]} {
close $f
break
}
puts "Read line: $line"
}
Read and print out the contents of a file by fixed-size records: set f [open somefile.dat]
fconfigure $f -translation binary
set recordSize 40
while {1} {
set record [read $f $recordSize]
if {[eof $f]} {
close $f
break
}
puts "Read record: $record"
}
} text/html} \ -set mime_type text/html \ -set title en:eof.n \ -set lang en ::xowiki::Page create ::xowiki::page25 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Returns a TCL_ERROR 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 info argument is provided
and is non-empty, it is used to initialize the global variable errorInfo.
errorInfo is used to accumulate a stack trace of what was in progress when
an error occurred; as nested commands unwind, the Tcl interpreter adds
information to errorInfo. If the info argument is present, it is used to
initialize errorInfo and the first increment of unwind information will
not be added by the Tcl interpreter. In other words, the command containing
the error command will not appear in errorInfo; in its place will be info.
This feature is most useful in conjunction with the catch command: if a
caught error cannot be handled successfully, info can be used to return
a stack trace reflecting the original point of occurrence of the error:
catch {...} errMsg
If the code argument is present, then its value is stored in the errorCode
global variable. This variable is intended to hold a machine-readable description
of the error in cases where such information is available; see the tclvars
manual page for information on the proper format for the variable. If the
code argument is not present, then errorCode is automatically reset to
‘‘NONE’’ by the Tcl interpreter as part of processing the error generated by
the command.
set savedInfo $errorInfo
...
error $errMsg $savedInfo
if {1+2 != 3} {
error "something is very wrong with addition"
}
} text/html} \ -set mime_type text/html \ -set title en:error.n \ -set lang en ::xowiki::Page create ::xowiki::page26 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Eval takes one or more arguments, which together comprise a Tcl script containing one or more commands. 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). Note that the list command quotes sequences of words in such a way that they are not further expanded by the eval command.
proc lprepend {varName args} {
upvar 1 $varName var
# Ensure that the variable exists and contains a list
lappend var
# Now we insert all the arguments in one go
set var [eval [list linsert $var 0] $args]
}
} text/html} \ -set mime_type text/html \ -set title en:eval.n \ -set lang en ::xowiki::Page create ::xowiki::page27 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command treats its arguments as the specification of one or more subprocesses to execute. The arguments take the form of a standard shell pipeline where each arg becomes one word of a command, and each distinct command becomes a subprocess.
If the initial arguments to exec start with - then they are treated as command-line switches and are not part of the pipeline specification. The following switches are currently supported:
If an arg (or pair of args) has one of the forms described below then it is used by exec to control the flow of input and output among the subprocess(es). Such arguments will not be passed to the subprocess(es). In forms such as ‘‘< fileName’’ fileName may either be in a separate argument from ‘‘<’’ or in the same argument with no intervening space (i.e. ‘‘<fileName’’).
If standard output has not been redirected then the exec command returns the standard output from the last command in the pipeline. If any of the commands in the pipeline exit abnormally or are killed or suspended, then exec will return an error and the error message will include the pipeline’s output followed by error messages describing the abnormal terminations; the errorCode variable will contain additional information about the last abnormal termination encountered. If any of the commands writes to its standard error file and that standard error isn’t redirected, then exec will return an error; the error message will include the pipeline’s standard output, followed by messages about abnormal terminations (if any), followed by the standard error output.
If the last character of the result or error message is a newline then that character is normally deleted from the result or error message. This is consistent with other Tcl return values, which don’t normally end with newlines. However, if -keepnewline is specified then the trailing newline is retained.
If standard input isn’t redirected with ‘‘<’’ or ‘‘<<’’ or ‘‘<@’’ then the standard input for the first command in the pipeline is taken from the application’s current standard input.
If the last arg is ‘‘&’’ then the pipeline will be executed in background. In this case the exec command will return a list whose elements are the process identifiers for all of the subprocesses in the pipeline. The standard output from the last command in the pipeline will go to the application’s standard output if it hasn’t been redirected, and error output from all of the commands in the pipeline will go to the application’s standard error file unless redirected.
The first word in each command is taken as the command name; tilde-substitution is performed on it, and if the result contains no slashes then the directories in the PATH environment variable are searched for an executable by the given name. If the name contains a slash then it must refer to an executable reachable from the current directory. No ‘‘glob’’ expansion or other shell-like substitutions are performed on the arguments to commands.
The Tk console text widget does not provide real standard IO capabilities. Under Tk, when redirecting from standard input, all applications will see an immediate end-of-file; information redirected to standard output or standard error will be discarded.
Either forward or backward slashes are accepted as path separators for arguments to Tcl commands. When executing an application, the path name specified for the application may also contain forward or backward slashes as path separators. Bear in mind, however, that most Windows applications accept arguments with forward slashes only as option delimiters and backslashes only in paths. Any arguments to an application that specify a path name with forward slashes will not automatically be converted to use the backslash character. If an argument contains forward slashes as the path separator, it may or may not be recognized as a path name, depending on the program.
Additionally, when calling a 16-bit DOS or Windows 3.X application, all path names must use the short, cryptic, path format (e.g., using ‘‘applba~1.def’’ instead of ‘‘applbakery.default’’), which can be obtained with the file attributes $fileName -shortname command.
Two or more forward or backward slashes in a row in a path refer to a network path. For example, a simple concatenation of the root directory c:/ with a subdirectory /windows/system will yield c://windows/system (two slashes together), which refers to the mount point called system on the machine called windows (and the c:/ is ignored), and is not equivalent to c:/windows/system, which describes a directory on the current computer. The file join command should be used to concatenate path components.
Note that there are two general types of Win32 console applications:1) CLI -- CommandLine Interface, simple stdio exchange. netstat.exe for example.
2) TUI -- Textmode User Interface, any application that accesses the console API for doing such things as cursor movement, setting text color, detecting key presses and mouse movement, etc. An example would be telnet.exe from Windows 2000. These types of applications are not common in a windows environment, but do exist.
The directory from which the Tcl executable was loaded.
The current directory.
The Windows NT 32-bit system directory.
The Windows NT 16-bit system directory.
The Windows NT home directory.
The directories listed in the path.
In order to execute shell built-in commands like dir and copy, the caller must prepend the desired command with ‘‘cmd.exe /c ’’ because built-in commands are not implemented using executables.
The directory from which the Tcl executable was loaded.
The current directory.
The Windows 9x system directory.
The Windows 9x home directory.
The directories listed in the path.
In order to execute shell built-in commands like dir and copy, the caller must prepend the desired command with ‘‘command.com /c ’’ because built-in commands are not implemented using executables.
Once a 16-bit DOS application has read standard input from a console and then quit, all subsequently run 16-bit DOS applications will see the standard input as already closed. 32-bit applications do not have this problem and will run correctly, even after a 16-bit DOS application thinks that standard input is closed. There is no known workaround for this bug at this time.
Redirection between the NUL: device and a 16-bit application does not always work. When redirecting from NUL:, some applications may hang, others will get an infinite stream of ‘‘0x01’’ bytes, and some will actually correctly get an immediate end-of-file; the behavior seems to depend upon something compiled into the application itself. When redirecting greater than 4K or so to NUL:, some applications will hang. The above problems do not happen with 32-bit applications.
All DOS 16-bit applications are run synchronously. All standard input from a pipe to a 16-bit DOS application is collected into a temporary file; the other end of the pipe must be closed before the 16-bit DOS application begins executing. All standard output or error from a 16-bit DOS application to a pipe is collected into temporary files; the application must terminate before the temporary files are redirected to the next stage of the pipeline. This is due to a workaround for a Windows 95 bug in the implementation of pipes, and is how the standard Windows 95 DOS shell handles pipes itself.
Certain applications, such as command.com, should not be executed interactively. Applications which directly access the console window, rather than reading from their standard input and writing to their standard output may fail, hang Tcl, or even hang the system if their own private console window is not available to them.
To
execute a simple program and get its result:
exec uname -a
To execute a program that can return a non-zero result, you should wrap
the call to exec in catch and check what the contents of the global errorCode
variable is if you have an error:
set status 0
When translating a command from a Unix shell invocation, care should be
taken over the fact that single quote characters have no special significance
to Tcl. Thus:
if {[catch {exec grep foo bar.txt} results]} {
if {[lindex $::errorCode 0] eq "CHILDSTATUS"} {
set status [lindex $::errorCode 2]
} else {
# Some kind of unexpected failure
}
}
awk ’{sum += $1} END {print sum}’ numbers.list
would be translated into something like:
exec awk {{sum += $1} END {print sum}} numbers.list
If you are converting invocations involving shell globbing, you should
remember that Tcl does not handle globbing or expand things into multiple
arguments by default. Instead you should write things like this:
eval [list exec ls -l] [glob *.tcl]
Windows Examples
Here are some examples of the use of the exec command on
Windows.
To start an instance of notepad editing a file without waiting
for the user to finish editing the file:
exec notepad myfile.txt &
To print a text file using notepad:
exec notepad /p myfile.txt
If a program calls other programs, such as is common with compilers, then
you may need to resort to batch files to hide the console windows that
sometimes pop up:
exec cmp.bat somefile.c -o somefile
With the file cmp.bat looking something like:
@gcc %1 %2 %3 %4 %5 %6 %7 %8 %9
Sometimes you need to be careful, as different programs may have the same
name and be in the path. It can then happen that typing a command at the
DOS prompt finds a different program than the same command run via exec.
This is because of the (documented) differences in behaviour between exec
and DOS batch files.
When in doubt, use the command auto_execok: it will
return the complete path to the program as seen by the exec command. This
applies especially when you want to run "internal" commands like dir from
a Tcl script (if you just want to list filenames, use the glob command.)
To do that, use this:
eval [list exec] [auto_execok dir] [list *.tcl]
} text/html} \ -set mime_type text/html \ -set title en:exec.n \ -set lang en ::xowiki::Page create ::xowiki::page28 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Terminate the process, returning returnCode to the system as the exit status. If returnCode isn’t specified then it defaults to 0.
proc main {} {
# ... put the real main code in here ...
}
if {[catch {main} msg]} {
puts stderr "unexpected script error: $msg"
if {[info exist env(DEBUG)]} {
puts stderr "---- BEGIN TRACE ----"
puts stderr $errorInfo
puts stderr "---- END TRACE ----"
}
# Reserve code 1 for "expected" error exits...
exit 2
}
} text/html} \ -set mime_type text/html \ -set title en:exit.n \ -set lang en ::xowiki::Page create ::xowiki::page29 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Concatenates args (adding separator spaces between
them), evaluates the result as a Tcl expression, and returns the value.
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
expr 8.2 + 6
evaluates to 14.2. Tcl expressions differ from C expressions in the way that
operands are specified. Also, 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’s instructions. Where possible, operands are interpreted as integer values. Integer values may be specified in decimal (the normal case), in octal (if the first character of the operand is 0), or in hexadecimal (if the first two characters of the operand are 0x). 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 (note that all literal operands that are not numeric or boolean must be quoted with either braces or with double quotes), then an operand is left as a string (and only a limited set of operators may be applied to it).
On 32-bit systems, integer values MAX_INT (0x7FFFFFFF) and MIN_INT (-0x80000000) will be represented as 32-bit values, and integer values outside that range will be represented as 64-bit values (if that is possible at all.)
Operands may be specified in any of the following ways:
Where the above substitutions occur (e.g. inside quoted strings), they are performed by the expression’s instructions. However, the command parser may already have performed one round of substitution 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 command on the left side of each of the lines below will produce
the value on the right side of the line:
expr 3.1 + $a 6.1
Operators
expr 2 + "$a.$b" 5.6
expr 4*[llength "6 2"] 8
expr {{word one} < "word $a"} 0
The valid operators are listed below, grouped in decreasing order of precedence:
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 command
expr 4*2 < 7
returns 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 the command
expr {$v ? [a] : [b]}
only one of [a] or [b] will actually be evaluated, depending on the value
of $v. Note, however, that this is only true if the entire expression is
enclosed in braces; otherwise the Tcl parser will evaluate both [a] and
[b] before invoking the expr command.
Tcl supports the following
mathematical functions in expressions, all of which work solely with floating-point
numbers unless otherwise noted:
abs cosh log sqrt
abs(arg)
acos double log10 srand
asin exp pow tan
atan floor rand tanh
atan2 fmod round wide
ceil hypot sin
cos int sinh
In addition to these predefined functions, applications may define additional functions using Tcl_CreateMathFunc().
All internal computations involving integers are done with the C type long, 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 behavior of some routines in the local C library, so it should be regarded as unreliable. In any case, integer overflow and underflow are generally not detected reliably for intermediate results. Floating-point overflow and underflow are detected to the degree supported by the hardware, which is generally pretty reliable.
Conversion
among internal representations for integer, floating-point, and 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,
expr 5 / 4
returns 1, while
expr 5 / 4.0
both return 1.25. Floating-point values are always returned with a ‘‘.’’ or an
e so that they will not look like integer values. For example,
expr 5 / ( [string length "abcd"] + 0.0 )
expr 20.0/5.0
returns 4.0, not 4.
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, except in the case
of the eq and ne operators. 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 commands
expr {"0x03" > "2"}
both return 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. Because of Tcl’s tendency to treat values as
numbers whenever possible, it isn’t generally a good idea to use operators
like == when you really want string comparison and the values of the operands
could be arbitrary; it’s better in these cases to use the eq or ne operators,
or the string command instead.
expr {"0y" < "0x12"}
Enclose expressions in braces for the best speed and the smallest storage requirements. This allows the Tcl bytecode compiler to generate the best code.
As mentioned
above, expressions are substituted twice: once by the Tcl parser and once
by the expr command. For example, the commands
set a 3
return 11, not a multiple of 4. This is because the Tcl parser will first
substitute $a + 2 for the variable b, then the expr command will evaluate
the expression $a + 2*4.
set b {$a + 2}
expr $b*4
Most expressions do not require a second round of substitutions. Either they are enclosed in braces or, if not, their variable and command substitutions yield numbers or strings that don’t themselves require substitutions. However, because a few unbraced expressions need two rounds of substitutions, the bytecode compiler must emit additional instructions to handle this situation. The most expensive code is required for unbraced expressions that contain command substitutions. These expressions must be implemented by generating new code each time the expression is executed.
proc calc {x y} {
expr { ($x*$x - $y*$y) / exp($x*$x + $y*$y) }
}
Convert polar coordinates into cartesian coordinates: # convert from ($radius,$angle)
set x [expr { $radius * cos($angle) }]
set y [expr { $radius * sin($angle) }]
Convert cartesian coordinates into polar coordinates: # convert from ($x,$y)
set radius [expr { hypot($y, $x) }]
set angle [expr { atan2($y, $x) }]
Print a message describing the relationship of two string values to each
other: puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
Set a variable to whether an environment variable is both defined at all
and also set to a true boolean value: set isTrue [expr {
[info exists ::env(SOME_ENV_VAR)] &&
[string is true -strict $::env(SOME_ENV_VAR)]
}]
Generate a random integer in the range 0..99 inclusive: set randNum [expr { int(100 * rand()) }]
The fblocked command returns 1 if the most recent input operation on channelId returned less information than requested because all available input was exhausted. For example, if gets is invoked when there are only three characters available for input and no end-of-line sequence, gets returns an empty string and a subsequent call to fblocked will return 1.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
# This is called whenever either at least one byte of input # Create the server socket and enter the event-loop to wait
# This is called whenever a new client connects to the server
proc connect {chan host port} {
set clientName [format <%s:%d> $host $port]
puts "connection from $clientName"
fconfigure $chan -blocking 0 -buffering line
fileevent $chan readable [list echoLine $chan $clientName]
}
# data is available, or the channel was closed by the client.
proc echoLine {chan clientName} {
gets $chan line
if {[eof $chan]} {
puts "finishing connection from $clientName"
close $chan
} elseif {![fblocked $chan]} {
# Didn’t block waiting for end-of-line
puts "$clientName - $line"
puts $chan $line
}
}
# for incoming connections...
socket -server connect 12345
vwait forever
} text/html} \ -set mime_type text/html \ -set title en:fblocked.n \ -set lang en ::xowiki::Page create ::xowiki::page31 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
fconfigure channelId fconfigure channelId name fconfigure channelId name value ?name value ...?
The fconfigure command sets and retrieves options for channels.
ChannelId identifies the channel for which to set or query an option and must refer to an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
If no name or value arguments are supplied, the command returns a list containing alternating option names and values for the channel. If name is supplied but no value then the command returns the current value of the given option. If one or more pairs of name and value are supplied, the command sets each of the named options to the corresponding value; in this case the return value is an empty string.
The options described below are supported for all channels. In addition, each channel type may add options that only it supports. See the manual entry for the command that creates each type of channels for the options that that specific type of channel supports. For example, see the manual entry for the socket command for its additional options.
If a file contains pure binary data (for instance, a JPEG image), the encoding for the channel should be configured to be binary. Tcl will then assign no interpretation to the data in the file and simply read or write raw bytes. The Tcl binary command can be used to manipulate this byte-oriented data.
The default encoding for newly opened channels is the same platform- and locale-dependent system encoding used for interfacing with the operating system.
The value associated with -translation is a single item for read-only and write-only channels. The value is a two-element list for read-write channels; the read translation mode is the first element of the list, and the write translation mode is the second element. As a convenience, when setting the translation mode for a read-write channel you can specify a single value that will apply to both reading and writing. When querying the translation mode of a read-write channel, a two-element list will always be returned. The following values are currently supported:
The Tcl standard channels (stdin, stdout, and stderr) can be configured through this command like every other channel opened by the Tcl library. Beyond the standard options described above they will also support any special option according to their current type. If, for example, a Tcl application is started by the inet super-server common on Unix system its Tcl standard channels will be sockets and thus support the socket options.
fconfigure stdout -buffering none
Open a socket and read lines from it without ever blocking the processing
of other events: set s [socket some.where.com 12345]
fconfigure $s -blocking 0
fileevent $s readable "readMe $s"
proc readMe chan {
if {[gets $chan line] < 0} {
if {[eof $chan]} {
close $chan
return
}
# Could not read a complete line this time; Tcl’s
# internal buffering will hold the partial line for us
# until some more data is available over the socket.
} else {
puts stdout $line
}
}
Read a PPM-format image from a file: # Open the file and put it into Unix ASCII mode
set f [open teapot.ppm]
fconfigure $f -encoding ascii -translation lf
# Get the header
if {[gets $f] ne "P6"} {
error "not a raw-bits PPM"
}
# Read lines until we have got non-comment lines
# that supply us with three decimal values.
set words {}
while {[llength $words] < 3} {
gets $f line
if {[string match "#*" $line]} continue
lappend words [eval concat [scan $line %d%d%d]]
}
# Those words supply the size of the image and its
# overall depth per channel. Assign to variables.
foreach {xSize ySize depth} $words {break}
# Now switch to binary mode to pull in the data,
# one byte per channel (red,green,blue) per pixel.
fconfigure $f -translation binary
set numDataBytes [expr {3 * $xSize * $ySize}]
set data [read $f $numDataBytes]
close $f
} text/html} \ -set mime_type text/html \ -set title en:fconfigure.n \ -set lang en ::xowiki::Page create ::xowiki::page32 -noinit \ -set description {} \ -set nls_language en_US \ -set text {\[\[en:#toc\]\]
\n\ \n
\ \n
\nThe\nfcopy\ command\ copies\ data\ from\ one\ I/O\ channel,\ inchan\ to\ another\ I/O\ channel,\noutchan.\ The\ fcopy\ command\ leverages\ the\ buffering\ in\ the\ Tcl\ I/O\ system\nto\ avoid\ extra\ copies\ and\ to\ avoid\ buffering\ too\ much\ data\ in\ main\ memory\nwhen\ copying\ large\ files\ to\ slow\ destinations\ like\ network\ sockets.\
\nThe\nfcopy\ \ command\ transfers\ data\ from\ inchan\ until\ end\ of\ file\ or\ size\ bytes\nhave\ been\ \ transferred.\ If\ no\ -size\ argument\ is\ given,\ then\ the\ copy\ goes\nuntil\ end\ of\ file.\ All\ the\ data\ read\ from\ inchan\ is\ copied\ to\ outchan.\ Without\nthe\ -command\ option,\ fcopy\ blocks\ until\ the\ copy\ is\ complete\ and\ returns\nthe\ number\ of\ bytes\ written\ to\ outchan.\
\nThe\ -command\ argument\ makes\ fcopy\nwork\ in\ the\ background.\ In\ this\ case\ it\ returns\ immediately\ and\ the\ callback\nis\ invoked\ later\ when\ the\ copy\ completes.\ The\ callback\ is\ called\ with\ one\nor\ two\ additional\ \ arguments\ that\ indicates\ how\ many\ bytes\ were\ written\nto\ outchan.\ If\ an\ error\ occurred\ during\ the\ background\ copy,\ the\ second\nargument\ is\ the\ error\ string\ associated\ with\ the\ error.\ With\ a\ background\ncopy,\ it\ is\ not\ necessary\ to\ put\ inchan\ or\ outchan\ into\ non-blocking\ mode\;\nthe\ fcopy\ command\ takes\ care\ of\ that\ automatically.\ However,\ it\ is\ necessary\nto\ enter\ the\ event\ loop\ by\ using\ the\ vwait\ command\ or\ by\ using\ Tk.\
\nYou\ are\nnot\ allowed\ to\ do\ other\ I/O\ operations\ with\ inchan\ or\ outchan\ during\ a\nbackground\ fcopy.\ If\ either\ inchan\ or\ outchan\ get\ closed\ while\ the\ copy\nis\ in\ progress,\ the\ current\ copy\ is\ stopped\ and\ the\ command\ callback\ is\nnot\ made.\ If\ inchan\ is\ closed,\ then\ all\ data\ already\ queued\ for\ outchan\nis\ written\ out.\
\nNote\ that\ inchan\ can\ become\ readable\ during\ a\ background\ncopy.\ You\ should\ turn\ off\ any\ fileevent\ handlers\ during\ a\ background\ copy\nso\ those\ handlers\ do\ not\ interfere\ with\ the\ copy.\ Any\ I/O\ attempted\ by\ a\nfileevent\ handler\ will\ get\ a\ \"channel\ busy\"\ error.\
\nFcopy\ translates\ end-of-line\nsequences\ in\ inchan\ and\ outchan\ according\ to\ the\ -translation\ option\ for\nthese\ channels.\ See\ the\ manual\ entry\ for\ fconfigure\ for\ details\ on\ the\ -translation\noption.\ The\ translations\ mean\ that\ the\ number\ of\ bytes\ read\ from\ inchan\ncan\ be\ different\ than\ the\ number\ of\ bytes\ written\ to\ outchan.\ Only\ the\ number\nof\ bytes\ written\ to\ outchan\ is\ reported,\ either\ as\ the\ return\ value\ of\na\ synchronous\ fcopy\ or\ as\ the\ argument\ to\ the\ callback\ for\ an\ asynchronous\nfcopy.\
\nFcopy\ obeys\ the\ encodings\ configured\ for\ the\ channels.\ This\ means\nthat\ the\ incoming\ characters\ are\ converted\ internally\ first\ UTF-8\ and\ then\ninto\ the\ encoding\ of\ the\ channel\ fcopy\ writes\ to.\ See\ the\ manual\ entry\ for\nfconfigure\ for\ details\ on\ the\ -encoding\ option.\ No\ conversion\ is\ done\ if\nboth\ channels\ are\ set\ to\ encoding\ \"binary\".\ If\ only\ the\ output\ channel\ is\nset\ to\ encoding\ \"binary\"\ the\ system\ will\ write\ the\ internal\ UTF-8\ representation\nof\ the\ incoming\ characters.\ If\ only\ the\ input\ channel\ is\ set\ to\ encoding\n\"binary\"\ the\ system\ will\ assume\ that\ the\ incoming\ bytes\ are\ valid\ UTF-8\ncharacters\ and\ convert\ them\ according\ to\ the\ output\ encoding.\ The\ behaviour\nof\ the\ system\ for\ bytes\ which\ are\ not\ valid\ UTF-8\ characters\ is\ undefined\nin\ this\ case.\ \n
\ \n
\nThis\ first\ example\ shows\ how\ the\ callback\ gets\ passed\nthe\ number\ of\ bytes\ transferred.\ It\ also\ uses\ vwait\ to\ put\ the\ application\ninto\ the\ event\ loop.\ Of\ course,\ this\ simplified\ example\ could\ be\ done\ without\nthe\ command\ \ callback.\
\n
\n \nproc \;Cleanup \;\{in \;out \;bytes \;\{error \;\{\}\}\} \;\{
The\ second\ example\ copies\ in\ chunks\ and\ tests\ for\ end\ of\ file\ in\ the\ command\ncallback\
\n \; \; \; \;global \;total
\n \; \; \; \;set \;total \;\$bytes
\n \; \; \; \;close \;\$in
\n \; \; \; \;close \;\$out
\n \; \; \; \;if \;\{\[string \;length \;\$error\] \;!= \;0\} \;\{
\n \; \; \; \;# \;error \;occurred \;during \;the \;copy
\n \; \; \; \;\}
\n\}
\nset \;in \;\[open \;\$file1\]
\nset \;out \;\[socket \;\$server \;\$port\]
\nfcopy \;\$in \;\$out \;-command \;\[list \;Cleanup \;\$in \;\$out\]
\nvwait \;total
\n\n
\n
\n \nproc \;CopyMore \;\{in \;out \;chunk \;bytes \;\{error \;\{\}\}\} \;\{
\ \n
\n \; \; \; \;global \;total \;done
\n \; \; \; \;incr \;total \;\$bytes
\n \; \; \; \;if \;\{(\[string \;length \;\$error\] \;!= \;0) \;|| \;\[eof \;\$in\] \;\{
\n \; \; \; \;set \;done \;\$total
\n \; \; \; \;close \;\$in
\n \; \; \; \;close \;\$out
\n \; \; \; \;\} \;else \;\{
\n \; \; \; \;fcopy \;\$in \;\$out \;-command \;\[list \;CopyMore \;\$in \;\$out \;\$chunk\] \;\\
\n \; \; \; \; \; \; \; \;-size \;\$chunk
\n \; \; \; \;\}
\n\}
\nset \;in \;\[open \;\$file1\]
\nset \;out \;\[socket \;\$server \;\$port\]
\nset \;chunk \;1024
\nset \;total \;0
\nfcopy \;\$in \;\$out \;-command \;\[list \;CopyMore \;\$in \;\$out \;\$chunk\] \;-size \;\$chunk
\nvwait \;done
\n\n
\ \n
\n\n
\n
\n\n text/html} \ -set mime_type text/html \ -set title en:fcopy.n \ -set lang en ::xowiki::Page create ::xowiki::page33 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command provides several operations on a file’s name or attributes. Name is the name of a file; if it starts with a tilde, then tilde substitution is done before executing the command (see the manual entry for filename for details). Option indicates what to do with the file name. Any unique abbreviation for option is acceptable. The valid options are:
This subcommand returns or sets platform specific values associated with a file. The first form returns a list of the platform specific flags and their values. The second form returns the value for the specific option. The third form sets one or more of the values. The values are as follows:
On Unix, -group gets or sets the group name for the file. A group id can be given to the command, but it returns a group name. -owner gets or sets the user name of the owner of the file. The command returns the owner name, but the numerical id can be passed when setting the owner. -permissions sets or retrieves the octal code that [[en:chmod.1]] uses. This command does also has limited support for setting using the symbolic attributes for [[en:chmod.1]] , of the form [ugo]?[[+-=][rwxst],[...]], where multiple symbolic attributes can be separated by commas (example: u+s,go-rw add sticky bit for user, remove read and write permissions for group and other). A simplified ls style string, of the form rwxrwxrwx (must be 9 characters), is also supported (example: rwxr-xr-t is equivalent to 01755).
On Windows, -archive gives the value or sets or clears the archive attribute of the file. -hidden gives the value or sets or clears the hidden attribute of the file. -longname will expand each path element to its long version. This attribute cannot be set. -readonly gives the value or sets or clears the readonly attribute of the file. -shortname gives a string where every path element is replaced with its short (8.3) version of the name. This attribute cannot be set. -system gives or sets or clears the value of the system attribute of the file.
On Macintosh, -creator gives or sets the Finder creator type of the file. -hidden gives or sets or clears the hidden attribute of the file. -readonly gives or sets or clears the readonly attribute of the file. Note that directories can only be locked if File Sharing is turned on. -type gives or sets the Finder file type for the file.
The first form makes a copy of the file or directory source under the pathname target. If target is an existing directory, then the second form is used. The second form makes a copy inside targetDir of each source file listed. If a directory is specified as a source, then the contents of the directory will be recursively copied into targetDir. Existing files will not be overwritten unless the -force option is specified. When copying within a single filesystem, file copy will copy soft links (i.e. the links themselves are copied, not the things they point to). Trying to overwrite a non-empty directory, overwrite a directory with a file, or overwrite a file with a directory will all result in errors even if -force was specified. Arguments are processed in the order specified, halting at the first error, if any. A -- marks the end of switches; the argument following the -- will be treated as a source even if it starts with a -.
file dirname c:/
returns c:/.
Note that tilde substitution will only be performed if it
is necessary to complete the command. For example,
file dirname ~/src/foo.c
returns ~/src, whereas
file dirname ~
returns /home (or something similar).
file join a b /foo bar
returns /foo/bar.
Note that any of the names can contain separators, and that the result is always canonical for the current platform: / for Unix and Windows, and : for Macintosh.
Returns a unique normalized path representation for the file-system object (file, directory, link, etc), whose string value can be used as a unique identifier for it. A normalized path is an absolute path which has all ’../’, ’./’ removed. Also it is one which is in the ‘‘standard’’ format for the native platform. On MacOS, Unix, this means the segments leading up to the path must be free of symbolic links/aliases (but the very last path component may be a symbolic link), and on Windows it also means we want the long form with that form’s case-dependence (which gives us a unique, case-dependent path). The one exception concerning the last link in the path is necessary, because Tcl or the user may wish to operate on the actual symbolic link itself (for example ’file delete’, ’file rename’, ’file copy’ are defined to operate on symbolic links, not on the things that they point to).
The first form takes the file or directory specified by pathname source and renames it to target, moving the file if the pathname target specifies a name in a different directory. If target is an existing directory, then the second form is used. The second form moves each source file or directory into the directory targetDir. Existing files will not be overwritten unless the -force option is specified. When operating inside a single filesystem, Tcl will rename symbolic links rather than the things that they point to. Trying to overwrite a non-empty directory, overwrite a directory with a file, or a file with a directory will all result in errors. Arguments are processed in the order specified, halting at the first error, if any. A -- marks the end of switches; the argument following the -- will be treated as a source even if it starts with a -.
file split /foo/~bar/baz
returns / foo ./~bar baz to ensure that later commands that use the third component do not attempt to perform tilde substitution.
proc findMatchingCFiles {dir} {
set files {}
switch $::tcl_platform(platform) {
windows {
set ext .obj
}
unix {
set ext .o
}
}
foreach file [glob -nocomplain -directory $dir *.c] {
set objectFile [file tail [file rootname $file]]$ext
if {[file exists $objectFile]} {
lappend files $file
}
}
return $files
}
Rename a file and leave a symbolic link pointing from the old location
to the new place: set oldName foobar.txt
set newName foo/bar.txt
# Make sure that where we’re going to move to exists...
if {![file isdirectory [file dirname $newName]]} {
file mkdir [file dirname $newName]
}
file rename $oldName $newName
file link -symbolic $oldName $newName
} text/html} \ -set mime_type text/html \ -set title en:file.n \ -set lang en ::xowiki::Page create ::xowiki::page34 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
fileevent channelId writable ?script?
This command is used to create file event handlers. A file event handler is a binding between a channel and a script, such that the script is evaluated whenever the channel becomes readable or writable. File event handlers are most commonly used to allow data to be received from another process on an event-driven basis, so that the receiver can continue to interact with the user while waiting for the data to arrive. If an application invokes gets or read on a blocking channel when there is no input data available, the process will block; until the input data arrives, it will not be able to service other events, so it will appear to the user to ‘‘freeze up’’. With fileevent, the process can tell when data is present and only invoke gets or read when they won’t block.
The channelId argument to fileevent refers to an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
If the script argument is specified, then fileevent creates a new event handler: script will be evaluated whenever the channel becomes readable or writable (depending on the second argument to fileevent). In this case fileevent returns an empty string. The readable and writable event handlers for a file are independent, and may be created and deleted separately. However, there may be at most one readable and one writable handler for a file at a given time in a given interpreter. If fileevent is called when the specified handler already exists in the invoking interpreter, the new script replaces the old one.
If the script argument is not specified, fileevent returns the current script for channelId, or an empty string if there is none. If the script argument is specified as an empty string then the event handler is deleted, so that no script will be invoked. A file event handler is also deleted automatically whenever its channel is closed or its interpreter is deleted.
A channel is considered to be readable if there is unread data available on the underlying device. A channel is also considered to be readable if there is unread data in an input buffer, except in the special case where the most recent attempt to read from the channel was a gets call that could not find a complete line in the input buffer. This feature allows a file to be read a line at a time in nonblocking mode using events. A channel is also considered to be readable if an end of file or error condition is present on the underlying file or device. It is important for script to check for these conditions and handle them appropriately; for example, if there is no special check for end of file, an infinite loop may occur where script reads no data, returns, and is immediately invoked again.
A channel is considered to be writable if at least one byte of data can be written to the underlying file or device without blocking, or if an error condition is present on the underlying file or device.
Event-driven I/O works best for channels that have been placed into nonblocking mode with the fconfigure command. In blocking mode, a puts command may block if you give it more data than the underlying file or device can accept, and a gets or read command will block if you attempt to read more data than is ready; no events will be processed while the commands block. In nonblocking mode puts, read, and gets never block. See the documentation for the individual commands for information on how they handle blocking and nonblocking channels.
The script for a file event is executed at global level (outside the context of any Tcl procedure) in the interpreter in which the fileevent command was invoked. If an error occurs while executing the script then the bgerror mechanism is used to report the error. In addition, the file event handler is deleted if it ever returns an error; this is done in order to prevent infinite loops due to buggy handlers.
proc GetData {chan} {
if {![eof $chan]} {
puts [gets $chan]
}
}
fileevent $chan readable [list GetData $chan]
fileevent is based on the addinput command created by Mark Diekhans.
} text/html} \ -set mime_type text/html \ -set title en:fileevent.n \ -set lang en ::xowiki::Page create ::xowiki::page35 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
All Tcl commands and C procedures that take file names as arguments expect the file names to be in one of three forms, depending on the current platform. On each platform, Tcl supports file names in the standard forms(s) for that platform. In addition, on all platforms, Tcl supports a Unix-like syntax intended to provide a convenient way of constructing simple file names. However, scripts that are intended to be portable should not assume a particular form for file names. Instead, portable scripts must use the file split and file join commands to manipulate file names (see the file manual entry for more details).
File names are grouped into three general types based on the starting point for the path used to specify the file: absolute, relative, and volume-relative. Absolute names are completely qualified, giving a path to the file relative to a particular volume and the root directory on that volume. Relative names are unqualified, giving a path to the file relative to the current working directory. Volume-relative names are partially qualified, either giving the path relative to the root directory on the current volume, or relative to the current directory of the specified volume. The file pathtype command can be used to determine the type of a given path.
The rules for native names depend on the value reported in the Tcl array element tcl_platform(platform) :
In addition to Macintosh style names, Tcl also supports a subset of Unix-like names. If a path contains no colons, then it is interpreted like a Unix path. Slash is used as the path separator. The file name . refers to the current directory, and .. refers to the parent of the current directory. However, some names like / or /.. have no mapping, and are interpreted as Macintosh names. In general, commands that generate file names will return Macintosh style names, but commands that accept file names will take both Macintosh and Unix-style names.
The following examples illustrate various forms of path names:
In addition to the file name rules described above, Tcl also supports csh-style tilde substitution. If a file name starts with a tilde, then the file name will be interpreted as if the first element is replaced with the location of the home directory for the given user. If the tilde is followed immediately by a separator, then the $HOME environment variable is substituted. Otherwise the characters between the tilde and the next separator are taken as a user name, which is used to retrieve the user’s home directory for substitution.
The Macintosh and Windows platforms do not support tilde substitution when a user name follows the tilde. On these platforms, attempts to use a tilde followed by a user name will generate an error that the user does not exist when Tcl attempts to interpret that part of the path or otherwise access the file. The behaviour of these paths when not trying to interpret them is the same as on Unix. File names that have a tilde without a user name will be correctly substituted using the $HOME environment variable, just like for Unix.
Not all file systems are case sensitive, so scripts should avoid code that depends on the case of characters in a file name. In addition, the character sets allowed on different devices may differ, so scripts should choose file names that do not contain special characters like: <>:"/\|. The safest approach is to use names consisting of alphanumeric characters only. Also Windows 3.1 only supports file names with a root of no more than 8 characters and an extension of no more than 3 characters.
On Windows platforms there are file and path length restrictions. Complete paths or filenames longer than about 260 characters will lead to errors in most file operations.
Another Windows peculiarity is that any number of trailing dots ’.’ in filenames are totally ignored, so, for example, attempts to create a file or directory with a name "foo." will result in the creation of a file/directory with name "foo". This fact is reflected in the results of ’file normalize’. Furthermore, a file name consisting only of dots ’.........’ or dots with trailing characters ’.....abc’ is illegal.
} text/html} \ -set mime_type text/html \ -set title en:filename.n \ -set lang en ::xowiki::Page create ::xowiki::page36 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Flushes any output that has been buffered for channelId.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdout or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension. The channel must have been opened for writing.
If the channel is in blocking mode the command does not return until all the buffered output has been flushed to the channel. If the channel is in nonblocking mode, the command may return before all buffered output has been flushed; the remainder will be flushed in the background as fast as the underlying file or device is able to absorb it.
puts -nonewline "Please type your name: "
flush stdout
gets stdin name
puts "Hello there, $name!"
} text/html} \ -set mime_type text/html \ -set title en:flush.n \ -set lang en ::xowiki::Page create ::xowiki::page37 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
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. If a break command is invoked within body or next, then the for command will return immediately. The operation of break and continue are similar to the corresponding statements in C. For returns an empty string.
Note: test should almost always be enclosed in braces. If not, variable substitutions will be made before the for command starts executing, which means that variable changes made by the loop body will not be considered in the expression. This is likely to result in an infinite loop. If test is enclosed in braces, variable substitutions are delayed until the expression is evaluated (before each loop iteration), so changes in the variables will be visible. See below for an example:
for {set x 0} {$x<10} {incr x} {
puts "x is $x"
}
Either loop infinitely or not at all because the expression being evaluated
is actually the constant, or even generate an error! The actual behaviour
will depend on whether the variable x exists before the for command is
run and whether its value is a value that is less than or greater than/equal
to ten, and this is because the expression will be substituted before the
for command is executed. for {set x 0} $x<10 {incr x} {
puts "x is $x"
}
Print out the powers of two from 1 to 1024: for {set x 1} {$x<=1024} {set x [expr {$x * 2}]} {
puts "x is $x"
}
} text/html} \ -set mime_type text/html \ -set title en:for.n \ -set lang en ::xowiki::Page create ::xowiki::page38 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The foreach command implements a loop where the loop variable(s) take on values from one or more lists. In the simplest case there is one loop variable, varname, and one list, list, that is a list of values to assign to varname. The body argument is a Tcl script. For each element of list (in order from first to last), foreach assigns the contents of the element to varname as if the lindex command had been used to extract the element, then calls the Tcl interpreter to execute body.
In the general case there can be more than one value list (e.g., list1 and list2), and each value list can be associated with a list of loop variables (e.g., varlist1 and varlist2). During each iteration of the loop the variables of each varlist are assigned consecutive values from the corresponding list. Values in each list are used in order from first to last, and each value is used exactly once. The total number of loop iterations is large enough to use up all the values from all the value lists. If a value list does not contain enough elements for each of its loop variables in each iteration, empty values are used for the missing elements.
The break and continue statements may be invoked inside body, with the same effect as in the for command. Foreach returns an empty string.
The following loop uses i and j as loop variables to iterate over
pairs of elements of a single list.
set x {}
The next loop uses i and j to iterate over two lists in parallel.
foreach {i j} {a b c d e f} {
lappend x $j $i
}
# The value of x is "b a d c f e"
# There are 3 iterations of the loop.
set x {}
The two forms are combined in the following example.
foreach i {a b c} j {d e f g} {
lappend x $i $j
}
# The value of x is "a d b e c f {} g"
# There are 4 iterations of the loop.
set x {}
foreach i {a b c} {j k} {d e f g} {
lappend x $i $j $k
}
# The value of x is "a d e b f g c {} {}"
# There are 3 iterations of the loop.
} text/html} \ -set mime_type text/html \ -set title en:foreach.n \ -set lang en ::xowiki::Page create ::xowiki::page39 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command generates a formatted string in the same way as the ANSI C sprintf procedure (it uses sprintf in its implementation). FormatString indicates how to format the result, using % conversion specifiers as in sprintf, and the additional arguments, if any, provide values to be substituted into the result. The return value from format is the formatted string.
The command operates by scanning formatString from left to right. Each character from the format string is appended to the result string unless it is a percent sign. If the character is a % then it is not copied to the result string. Instead, the characters following the % character are treated as a conversion specifier. The conversion specifier controls the conversion of the next successive arg to a particular format and the result is appended to the result string in place of the conversion specifier. If there are multiple conversion specifiers in the format string, then each one controls the conversion of one additional arg. The format command must be given enough args to meet the needs of all of the conversion specifiers in formatString.
Each conversion specifier may contain up to six different parts: an XPG3 position specifier, a set of flags, a minimum field width, a precision, a length modifier, and a conversion character. Any of these fields may be omitted except for the conversion character. The fields that are present must appear in the order given above. The paragraphs below discuss each of these fields in turn.
If the % is followed by a decimal number and a $, as in ‘‘%2$d’’, then the value to convert is not taken from the next sequential argument. Instead, it is taken from the argument indicated by the number, where 1 corresponds to the first arg. If the conversion specifier requires multiple arguments because of * characters in the specifier then successive arguments are used, starting with the argument given by the number. This follows the XPG3 conventions for positional specifiers. If there are any positional specifiers in formatString then all of the specifiers must be positional.
The second portion of a conversion specifier may contain any of the following flag characters, in any order:
The third portion of a conversion specifier is a number giving a minimum field width for this conversion. It is typically used to make columns line up in tabular printouts. If the converted argument contains fewer characters than the minimum field width then it will be padded so that it is as wide as the minimum field width. Padding normally occurs by adding extra spaces on the left of the converted argument, but the 0 and - flags may be used to specify padding with zeroes on the left or with spaces on the right, respectively. If the minimum field width is specified as * rather than a number, then the next argument to the format command determines the minimum field width; it must be a numeric string.
The fourth portion of a conversion specifier is a precision, which consists of a period followed by a number. The number is used in different ways for different conversions. For e, E, and f conversions it specifies the number of digits to appear to the right of the decimal point. For g and G conversions it specifies the total number of digits to appear, including those on both sides of the decimal point (however, trailing zeroes after the decimal point will still be omitted unless the # flag has been specified). For integer conversions, it specifies a minimum number of digits to print (leading zeroes will be added if necessary). For s conversions it specifies the maximum number of characters to be printed; if the string is longer than this then the trailing characters will be dropped. If the precision is specified with * rather than a number then the next argument to the format command determines the precision; it must be a numeric string.
The fifth part of a conversion specifier is a length modifier, which must be h or l. If it is h it specifies that the numeric value should be truncated to a 16-bit value before converting. This option is rarely useful. If it is l it specifies that the numeric value should be (at least) a 64-bit value. If neither h nor l are present, numeric values are interpreted as being values of the width of the native machine word, as described by tcl_platform(wordSize).
The last thing in a conversion specifier is an alphabetic character that determines what kind of conversion to perform. The following conversion characters are currently supported:
For the numerical conversions the argument being converted must be an integer or floating-point string; format converts the argument to binary and then converts it back to a string according to the conversion specifier.
The behavior of the format command is the same as the ANSI C sprintf procedure except for the following differences:
set us [lindex [time $someTclCode] 0]
puts [format "%.2f seconds to execute" [expr {$us / 1e6}]]
Create a packed X11 literal color specification: # Each color-component should be in range (0..255)
set color [format "#%02x%02x%02x" $r $g $b]
Use XPG3 format codes to allow reordering of fields (a technique that is
often used in localized message catalogs; see msgcat) without reordering
the data values passed to format: set fmt1 "Today, %d shares in %s were bought at $%.2f each"
puts [format $fmt1 123 "Global BigCorp" 19.37]
set fmt2 "Bought %2\$s equity ($%3$.2f x %1\$d) today"
puts [format $fmt2 123 "Global BigCorp" 19.37]
Print a small table of powers of three: # Set up the column widths
set w1 5
set w2 10
# Make a nice header (with separator) for the table first
set sep +-[string repeat - $w1]-+-[string repeat - $w2]-+
puts $sep
puts [format "| %-*s | %-*s |" $w1 "Index" $w2 "Power"]
puts $sep
# Print the contents of the table
set p 1
for {set i 0} {$i<=20} {incr i} {
puts [format "| %*d | %*ld |" $w1 $i $w2 $p]
set p [expr {wide($p) * 3}]
}
# Finish off by printing the separator again
puts $sep
This command reads the next line from channelId, returns everything in the line up to (but not including) the end-of-line character(s), and discards the end-of-line character(s).
ChannelId must be an identifier for an open channel such as the Tcl standard input channel (stdin), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension. The channel must have been opened for input.
If varName is omitted the line is returned as the result of the command. 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 returned.
If end of file occurs while scanning for an end of line, the command returns whatever input is available up to the end of file. If channelId is in nonblocking mode and there is not a full line of input available, the command returns an empty string and does not consume any input. If varName is specified and an empty string is returned in varName because of end-of-file or because of insufficient data in nonblocking mode, then the return count is -1. Note that if varName is not specified then the end-of-file and no-full-line-available cases can produce the same results as if there were an input line consisting only of the end-of-line character(s). The eof and fblocked commands can be used to distinguish these three cases.
set chan [open "some.file.txt"]
set lineNumber 0
while {[gets $chan line] >= 0} {
puts "[incr lineNumber]: $line"
}
close $chan
} text/html} \ -set mime_type text/html \ -set title en:gets.n \ -set lang en ::xowiki::Page create ::xowiki::page41 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command performs file name ‘‘globbing’’ in a fashion similar to the csh shell. It returns a list of the files whose names match any of the pattern arguments.
If the initial arguments to glob start with - then they are treated as switches. The following switches are currently supported:
The second form specifies types where all the types given must match. These are r, w, x as file permissions, and readonly, hidden as special permission cases. On the Macintosh, MacOS types and creators are also supported, where any item which is four characters long is assumed to be a MacOS type (e.g. TEXT). Items which are of the form {macintosh type XXXX} or {macintosh creator XXXX} will match types or creators respectively. Unrecognized types, or specifications of multiple MacOS types/creators will signal an error.
The two forms may be mixed, so -types {d f r w} will find all regular files OR directories that have both read AND write permissions. The following are equivalent:
except that the first case doesn’t return the trailing ‘‘/’’ and is more platform independent.
glob -type d *
glob */
The pattern arguments may contain any of the following special characters:
On Unix, as with csh, a ‘‘.’’ at the beginning of a file’s name or just after a ‘‘/’’ must be matched explicitly or with a {} construct, unless the ‘‘-types hidden’’ flag is given (since ‘‘.’’ at the beginning of a file’s name indicates that it is hidden). On other platforms, files beginning with a ‘‘.’’ are handled no differently to any others, except the special directories ‘‘.’’ and ‘‘..’’ which must be matched explicitly (this is to avoid a recursive pattern like ‘‘glob -join * * * *’’ from recursing up the directory hierarchy as well as down). In addition, all ‘‘/’’ characters must be matched explicitly.
If the first character in a pattern is ‘‘~’’ then it refers to the home directory for the user whose name follows the ‘‘~’’. If the ‘‘~’’ is followed immediately by ‘‘/’’ then the value of the HOME environment variable is used.
The glob command differs from csh globbing in two ways. First, it does not sort its result list (use the lsort command if you want the list sorted). Second, glob only returns the names of files that actually exist; in csh no check for existence is made unless a pattern contains a ?, *, or [] construct.
When the glob command returns relative paths whose filenames start with a tilde ‘‘~’’ (for example through glob * or glob -tails, the returned list will not quote the tilde with ‘‘./’’. This means care must be taken if those names are later to be used with file join, to avoid them being interpreted as absolute paths pointing to a given user’s home directory.
Unlike other Tcl commands that will accept both network and native style names (see the filename manual entry for details on how native and network names are specified), the glob command only accepts native names.
Since the backslash character has a special meaning to the glob command, glob patterns containing Windows style path separators need special care. The pattern C:\\foo\\* is interpreted as C:\foo\* where \f will match the single character f and \* will match the single character * and will not be interpreted as a wildcard character. One solution to this problem is to use the Unix style forward slash as a path separator. Windows style paths can be converted to Unix style paths with the command file join $path (or file normalize $path in Tcl 8.4).
glob *.tcl
Find all the Tcl files in the user’s home directory, irrespective of what
the current directory is: glob -directory ~ *.tcl
Find all subdirectories of the current directory: glob -type d *
Find all files whose name contains an "a", a "b" or the sequence "cde":
glob -type f *{a,b,cde}*
} text/html} \ -set mime_type text/html \ -set title en:glob.n \ -set lang en ::xowiki::Page create ::xowiki::page42 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command has no effect unless executed in the context of a proc body. If the global command is executed in the context of a proc body, it creates local variables linked to the corresponding global variables (and therefore these variables are listed by info locals).
If varname contains namespace qualifiers, the local variable’s name is the unqualified name of the global variable, as determined by the namespace tail command.
proc reset {} {
global a::x
set x 0
}
This procedure accumulates the strings passed to it in a global buffer,
separated by newlines. It is useful for situations when you want to build
a message piece-by-piece (as if with puts) but send that full message in
a single piece (e.g. over a connection opened with socket or as part of a
counted HTTP response). proc accum {string} {
global accumulator
append accumulator $string \n
}
} text/html} \ -set mime_type text/html \ -set title en:global.n \ -set lang en ::xowiki::Page create ::xowiki::page43 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The history command performs one of several operations related to recently-executed commands recorded in a history list. Each of these recorded commands is referred to as an ‘‘event’’. When specifying an event to the history command, the following forms may be used:
The history command can take any of the following forms:
Pre-8.0 Tcl had a complex history revision mechanism. The current mechanism is more limited, and the old history operations substitute and words have been removed. (As a consolation, the clear operation was added.)
The history option redo results in much simpler ‘‘history revision’’. When this option is invoked then the most recent event is modified to eliminate the history command and replace it with the result of the history command. If you want to redo an event without modifying history, then use the event operation to retrieve some event, and the add operation to add it to history and execute it.
} text/html} \ -set mime_type text/html \ -set title en:history.n \ -set lang en ::xowiki::Page create ::xowiki::page44 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
::[[en:http::config]] ?options?
::[[en:http::geturl]] url ?options?
::http::formatQuery key value ?key value ...?
::http::reset token ?why?
::[[en:http::wait]] token
::[[en:http::status]] token
::[[en:http::size]] token
::[[en:http::code]] token
::[[en:http::ncode]] token
::[[en:http::data]] token
::[[en:http::error]] token
::[[en:http::cleanup]] token
::[[en:http::register]] proto port command
::[[en:http::unregister]]
proto
The http package provides the client side of the HTTP/1.0 protocol. The package implements the GET, POST, and HEAD operations of HTTP/1.0. It allows configuration of a proxy host to get through firewalls. The package is compatible with the Safesock security policy, so it can be used by untrusted applets to do URL fetching from a restricted set of hosts. This package can be extended to support additional HTTP transport protocols, such as HTTPS, by providing a custom socket command, via ::http::register.
The ::http::geturl procedure does a HTTP transaction. Its options determine whether a GET, POST, or HEAD transaction is performed. The return value of ::http::geturl is a token for the transaction. The value is also the name of an array in the ::[[en:http]] namespace that contains state information about the transaction. The elements of this array are described in the STATE ARRAY section.
If the -command option is specified, then the HTTP operation is done in the background. ::http::geturl returns immediately after generating the HTTP request and the callback is invoked when the transaction completes. For this to work, the Tcl event loop must be active. In Tk applications this is always true. For pure-Tcl applications, the caller can use ::http::wait after calling ::http::geturl to start the event loop.
proc httpCallback {token} {
upvar #0 $token state
# Access state as a Tcl array
}
proc httpHandlerCallback {socket token} {
upvar #0 $token state
# Access socket, and state as a Tcl array
...
(example: set data [read $socket 1000];set nbytes [string length $data])
...
return nbytes
}
Pragma: no-cache
proc httpProgress {token total current} {
upvar #0 $token state
}
package require http
package require tls
::http::register https 443 ::tls::socket
set token [::http::geturl https://my.secure.site/]
For asynchronous ::http::geturl calls, all of the above error situations apply, except that if there’s any error while reading the HTTP reply headers or data, no exception is thrown. This is because after writing the HTTP headers, ::http::geturl returns, and the rest of the HTTP transaction occurs in the background. The command callback can check if any error occurred during the read by calling ::http::status to check the status and if its error, calling ::http::error to get the error message.
Alternatively, if the main program flow reaches a point where it needs to know the result of the asynchronous HTTP request, it can call ::http::wait and then check status and error, just as the callback does.
In any case, you must still call ::http::cleanup to delete the state array when you’re done.
There are other possible results of the HTTP transaction determined by examining the status from ::http::status. These are described below.
Another error possibility is that ::http::geturl is unable to write all the post query data to the server before the server responds and closes the socket. The error message is saved in the posterror status array element and then ::http::geturl attempts to complete the transaction. If it can read the server’s response it will end up with an ok status, otherwise it will have an eof status.
upvar #0 $token state
Once the data associated with the URL is no longer needed, the state array
should be unset to free up storage. The ::http::cleanup
procedure is provided
for that purpose. The following elements of the array are supported:
- body
- The contents of the URL. This will be empty if the -channel option has been specified. This value is returned by the ::http::data command.
- charset
- The value of the charset attribute from the Content-Type meta-data value. If none was specified, this defaults to the RFC standard iso8859-1, or the value of $::http::defaultCharset. Incoming text data will be automatically converted from this charset to utf-8.
- coding
- A copy of the Content-Encoding meta-data value.
- currentsize
- The current number of bytes fetched from the URL. This value is returned by the ::http::size command.
- error
- If defined, this is the error string seen when the HTTP transaction was aborted.
- http
- The HTTP status reply from the server. This value is returned by the ::http::code command. The format of this value is:
HTTP/1.0 code string
The code is a three-digit number defined in the HTTP standard. A code of 200 is OK. Codes beginning with 4 or 5 indicate errors. Codes beginning with 3 are redirection errors. In this case the Location meta-data specifies a new URL that contains the requested information.
array set meta $state(meta)
Some of the meta-data keys are listed below, but the HTTP standard defines more, and servers are free to add their own.
# Copy a URL to a file and print meta-data
proc httpcopy
{ url file {chunk 4096} } {
set out [open $file w]
set token [::http::geturl
$url -channel $out \
-progress httpCopyProgress
-blocksize $chunk]
close $out
# This ends the line started by httpCopyProgress
puts stderr ""
upvar #0 $token state
set max 0
foreach {name value} $state(meta) {
if {[string length $name] > $max} {
set max [string length $name]
}
if {[regexp -nocase ^location$ $name]} {
# Handle URL redirects
puts stderr "Location:$value"
return [httpcopy
[string trim $value] $file $chunk]
}
}
incr max
foreach {name value} $state(meta) {
puts [format "%-*s %s" $max $name: $value]
}
return $token
}
proc httpCopyProgress
{args} {
puts -nonewline stderr .
flush stderr
}
} text/html} \ -set mime_type text/html \ -set title en:http.n \ -set lang en ::xowiki::Page create ::xowiki::page45 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The if command evaluates expr1 as an expression (in the same way that expr evaluates its argument). The value of the expression must be a boolean (a numeric value, where 0 is false and anything is true, or a string value such as true or yes for true and false or no for false); if it is true then body1 is executed by passing it to the Tcl interpreter. Otherwise expr2 is evaluated as an expression and if it is true then body2 is executed, and so on. If none of the expressions evaluates to true 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.
if {$vbl == 1} { puts "vbl is one" }
With an else-clause: if {$vbl == 1} {
puts "vbl is one"
} else {
puts "vbl is not one"
}
With an elseif-clause too: if {$vbl == 1} {
puts "vbl is one"
} elseif {$vbl == 2} {
puts "vbl is two"
} else {
puts "vbl is not one or two"
}
Remember, expressions can be multi-line, but in that case it can be a good
idea to use the optional then keyword for clarity: if {
$vbl == 1 || $vbl == 2 || $vbl == 3
} then {
puts "vbl is one, two or three"
}
} text/html} \ -set mime_type text/html \ -set title en:if.n \ -set lang en ::xowiki::Page create ::xowiki::page46 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Increments the value stored in the variable whose name is varName. The value of the variable must be an integer. If increment is supplied then its value (which must be an integer) 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.
incr x
Add 42 to the contents of the variable x: incr x 42
Add the contents of the variable y to the contents of the variable x: incr x $y
Add nothing at all to the variable x (often useful for checking whether
an argument to a procedure is actually numeric and generating an error
if it is not): incr x 0
} text/html} \ -set mime_type text/html \ -set title en:incr.n \ -set lang en ::xowiki::Page create ::xowiki::page47 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command provides information about various internals of the Tcl interpreter. The legal option’s (which may be abbreviated) are:
proc printProc {procName} {
set result [list proc $procName]
set formals {}
foreach var [info args $procName] {
if {[info default $procName $var def]} {
lappend formals [list $var $def]
} else {
# Still need the list-quoting because variable
# names may properly contain spaces.
lappend formals [list $var]
}
}
puts [lappend result $formals [info body $procName]]
}
} text/html} \ -set mime_type text/html \ -set title en:info.n \ -set lang en ::xowiki::Page create ::xowiki::page48 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command makes it possible to create one or more new Tcl interpreters that co-exist with the creating interpreter in the same application. The creating interpreter is called the master and the new interpreter is called a slave. A master can create any number of slaves, and each slave can itself create additional slaves for which it is master, resulting in a hierarchy of interpreters.
Each interpreter is independent from the others: it has its own name space for commands, procedures, and global variables. A master interpreter may create connections between its slaves and itself using a mechanism called an alias. An alias is a command in a slave interpreter which, when invoked, causes a command to be invoked in its master interpreter or in another slave interpreter. The only other connections between interpreters are through environment variables (the env variable), which are normally shared among all interpreters in the application. Note that the name space for files (such as the names returned by the open command) is no longer shared between interpreters. Explicit commands are provided to share files and to transfer references to open files from one interpreter to another.
The interp command also provides support for safe interpreters. A safe interpreter is a slave whose functions have been greatly restricted, so that it is safe to execute untrusted scripts without fear of them damaging other interpreters or the application’s environment. For example, all IO channel creation commands and subprocess creation commands are made inaccessible to safe interpreters. See SAFE INTERPRETERS below for more information on what features are present in a safe interpreter. The dangerous functionality is not removed from the safe interpreter; instead, it is hidden, so that only trusted interpreters can obtain access to it. For a detailed explanation of hidden commands, see HIDDEN COMMANDS, below. The alias mechanism can be used for protected communication (analogous to a kernel call) between a slave interpreter and its master. See ALIAS INVOCATION, below, for more details on how the alias mechanism works.
A qualified interpreter name is a proper Tcl lists containing a subset of its ancestors in the interpreter hierarchy, terminated by the string naming the interpreter in its immediate master. Interpreter names are relative to the interpreter in which they are used. For example, if a is a slave of the current interpreter and it has a slave a1, which in turn has a slave a11, the qualified name of a11 in a is the list a1 a11.
The interp command, described below, accepts qualified interpreter names as arguments; the interpreter in which the command is being evaluated can always be referred to as {} (the empty list or string). Note that it is impossible to refer to a master (ancestor) interpreter by name in a slave interpreter except through aliases. Also, there is no global name by which one can refer to the first interpreter created in an application. Both restrictions are motivated by safety concerns.
The interp command is used to create, delete, and manipulate slave interpreters, and to share or transfer channels between interpreters. It can have any of several forms, depending on the option argument:
The command sets the maximum size of the Tcl call stack only. It cannot by itself prevent stack overflows on the C stack being used by the application. If your machine has a limit on the size of the C stack, you may get stack overflows before reaching the limit set by the command. If this happens, see if there is a mechanism in your system for increasing the maximum size of the C stack.
For
each slave interpreter created with the interp command, a new Tcl command
is created in the master interpreter with the same name as the new interpreter.
This command may be used to invoke various operations on the interpreter.
It has the following general form:
slave command ?arg arg ...?
Slave is the name of the interpreter, and command and the args determine
the exact behavior of the command. The valid forms of this command are:
The command sets the maximum size of the Tcl call stack only. It cannot by itself prevent stack overflows on the C stack being used by the application. If your machine has a limit on the size of the C stack, you may get stack overflows before reaching the limit set by the command. If this happens, see if there is a mechanism in your system for increasing the maximum size of the C stack.
A safe interpreter is one with restricted functionality, so that is safe to execute an arbitrary script from your worst enemy without fear of that script damaging the enclosing application or the rest of your computing environment. In order to make an interpreter safe, certain commands and variables are removed from the interpreter. For example, commands to create files on disk are removed, and the exec command is removed, since it could be used to cause damage through subprocesses. Limited access to these facilities can be provided, by creating aliases to the master interpreter which check their arguments carefully and provide restricted access to a safe subset of facilities. For example, file creation might be allowed in a particular subdirectory and subprocess invocation might be allowed for a carefully selected and fixed set of programs.
A safe interpreter is created by specifying the -safe switch to the interp create command. Furthermore, any slave created by a safe interpreter will also be safe.
A safe interpreter is created with
exactly the following set of built-in commands:
after append array binary
The following commands are hidden by interp create when it creates a safe
interpreter:
break case catch clock
close concat continue eof
error eval expr fblocked
fcopy fileevent flush for
foreach format gets global
if incr info interp
join lappend lindex linsert
list llength lrange lreplace
lsearch lsort namespace package
pid proc puts read
regexp regsub rename return
scan seek set split
string subst switch tell
time trace unset update
uplevel upvar variable vwait
while
cd encoding exec exit
These commands can be recreated later as Tcl procedures or aliases, or
re-exposed by interp expose.
fconfigure file glob load
open pwd socket source
The following commands from Tcl’s library of
support procedures are not present in a safe interpreter:
auto_exec_ok auto_import auto_load
Note in particular that safe interpreters have no default unknown command,
so Tcl’s default autoloading facilities are not available. Autoload access
to Tcl’s commands that are normally autoloaded:
auto_load_index auto_qualify unknown
auto_mkindex auto_mkindex_old
can only be provided by explicit definition of an unknown command in the
safe interpreter. This will involve exposing the source command. This is
most easily accomplished by creating the safe interpreter with Tcl’s Safe-Tcl
mechanism. Safe-Tcl provides safe versions of source, load, and other Tcl
commands needed to support autoloading of commands and the loading of packages.
auto_reset history
parray pkg_mkIndex
::pkg::create ::safe::interpAddToAccessPath
::safe::interpCreate ::safe::interpConfigure
::safe::interpDelete ::safe::interpFindInAccessPath
::safe::interpInit ::safe::setLogCmd
tcl_endOfWord tcl_findLibrary
tcl_startOfNextWord tcl_startOfPreviousWord
tcl_wordBreakAfter tcl_wordBreakBefore
In addition, the env variable is not present in a safe interpreter, so it cannot share environment variables with other interpreters. The env variable poses a security risk, because users can store sensitive information in an environment variable. For example, the PGP manual recommends storing the PGP private key protection password in the environment variable PGPPASS. Making this variable available to untrusted code executing in a safe interpreter would incur a security risk.
If extensions are loaded into a safe interpreter, they may also restrict their own functionality to eliminate unsafe commands. For a discussion of management of extensions for safety see the manual entries for Safe-Tcl and the load Tcl command.
A safe interpreter may not alter the recursion limit of any interpreter, including itself.
The alias mechanism has been carefully designed so that it can be used safely when an untrusted script is executing in a safe slave and the target of the alias is a trusted master. The most important thing in guaranteeing safety is to ensure that information passed from the slave to the master is never evaluated or substituted in the master; if this were to occur, it would enable an evil script in the slave to invoke arbitrary functions in the master, which would compromise security.
When the source for an alias is invoked in the slave interpreter, the usual Tcl substitutions are performed when parsing that command. These substitutions are carried out in the source interpreter just as they would be for any other command invoked in that interpreter. The command procedure for the source command takes its arguments and merges them with the targetCmd and args for the alias to create a new array of arguments. If the words of srcCmd were ‘‘srcCmd arg1 arg2 ... argN’’, the new set of words will be ‘‘targetCmd arg arg ... arg arg1 arg2 ... argN’’, where targetCmd and args are the values supplied when the alias was created. TargetCmd is then used to locate a command procedure in the target interpreter, and that command procedure is invoked with the new set of arguments. An error occurs if there is no command named targetCmd in the target interpreter. No additional substitutions are performed on the words: the target command procedure is invoked directly, without going through the normal Tcl evaluation mechanism. Substitutions are thus performed on each word exactly once: targetCmd and args were substituted when parsing the command that created the alias, and arg1 - argN are substituted when the alias’s source command is parsed in the source interpreter.
When writing the targetCmds for aliases in safe interpreters, it is very important that the arguments to that command never be evaluated or substituted, since this would provide an escape mechanism whereby the slave interpreter could execute arbitrary code in the master. This in turn would compromise the security of the system.
Safe interpreters greatly restrict the functionality available to Tcl programs executing within them. Allowing the untrusted Tcl program to have direct access to this functionality is unsafe, because it can be used for a variety of attacks on the environment. However, there are times when there is a legitimate need to use the dangerous functionality in the context of the safe interpreter. For example, sometimes a program must be sourced into the interpreter. Another example is Tk, where windows are bound to the hierarchy of windows for a specific interpreter; some potentially dangerous functions, e.g. window management, must be performed on these windows within the interpreter context.
The interp command provides a solution to this problem in the form of hidden commands. Instead of removing the dangerous commands entirely from a safe interpreter, these commands are hidden so they become unavailable to Tcl scripts executing in the interpreter. However, such hidden commands can be invoked by any trusted ancestor of the safe interpreter, in the context of the safe interpreter, using interp invoke. Hidden commands and exposed commands reside in separate name spaces. It is possible to define a hidden command and an exposed command by the same name within one interpreter.
Hidden commands in a slave interpreter can be invoked in the body of procedures called in the master during alias invocation. For example, an alias for source could be created in a slave interpreter. When it is invoked in the slave interpreter, a procedure is called in the master interpreter to check that the operation is allowable (e.g. it asks to source a file that the slave interpreter is allowed to access). The procedure then it invokes the hidden source command in the slave interpreter to actually source in the contents of the file. Note that two commands named source exist in the slave interpreter: the alias, and the hidden command.
Because a master interpreter may invoke a hidden command as part of handling an alias invocation, great care must be taken to avoid evaluating any arguments passed in through the alias invocation. Otherwise, malicious slave interpreters could cause a trusted master interpreter to execute dangerous commands on their behalf. See the section on ALIAS INVOCATION for a more complete discussion of this topic. To help avoid this problem, no substitutions or evaluations are applied to arguments of interp invokehidden.
Safe interpreters are not allowed to invoke hidden commands in themselves or in their descendants. This prevents safe slaves from gaining access to hidden functionality in themselves or their descendants.
The set of hidden commands in an interpreter can be manipulated by a trusted interpreter using interp expose and interp hide. The interp expose command moves a hidden command to the set of exposed commands in the interpreter identified by path, potentially renaming the command in the process. If an exposed command by the targeted name already exists, the operation fails. Similarly, interp hide moves an exposed command to the set of hidden commands in that interpreter. Safe interpreters are not allowed to move commands between the set of hidden and exposed commands, in either themselves or their descendants.
Currently, the names of hidden commands cannot contain namespace qualifiers, and you must first rename a command in a namespace to the global namespace before you can hide it. Commands to be hidden by interp hide are looked up in the global namespace even if the current namespace is not the global one. This prevents slaves from fooling a master interpreter into hiding the wrong command, by making the current namespace be different from the global one.
This mechanism is based on the Safe-Tcl prototype implemented by Nathaniel Borenstein and Marshall Rose.
interp alias {} getIndex {} lsearch {alpha beta gamma delta}
set idx [getIndex delta]
Executing an arbitrary command in a safe interpreter where every invokation
of lappend is logged: set i [interp create -safe]
interp hide $i lappend
interp alias $i lappend {} loggedLappend $i
proc loggedLappend {i args} {
puts "logged invokation of lappend $args"
# Be extremely careful about command construction
eval [linsert $args 0 \
interp invokehidden $i lappend]
}
interp eval $i $someUntrustedScript
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.
set data {1 2 3 4 5}
join $data ", "
=> 1, 2, 3, 4, 5
Using join to flatten a list by a single level: set data {1 {2 3} 4 {5 {6 7} 8}}
join $data
=> 1 2 3 4 5 {6 7} 8
} text/html} \ -set mime_type text/html \ -set title en:join.n \ -set lang en ::xowiki::Page create ::xowiki::page50 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command treats the variable given by varName as a list and appends 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 the values are appended as list elements 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.
% set var 1
1
% lappend var 2
1 2
% lappend var 3 4 5
1 2 3 4 5
} text/html} \ -set mime_type text/html \ -set title en:lappend.n \ -set lang en ::xowiki::Page create ::xowiki::page51 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The lindex command accepts a parameter, list, which it treats as a Tcl list. It also accepts zero or more indices into the list. The indices may be presented either consecutively on the command line, or grouped in a Tcl list and presented as a single argument.
If no indices
are presented, the command takes the form:
lindex list
or
lindex list {}
In this case, the return value of lindex is simply the value of the list
parameter.
When presented with a single index, the lindex command treats list as a Tcl list and returns the index’th element from it (0 refers to the first element of the list). 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 index is negative or greater than or equal to the number of elements in value, then an empty string is returned. If index has the value end, it refers to the last element in the list, and end-integer refers to the last element in the list minus the specified integer offset.
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. The command,
lindex $a 1 2 3
or
lindex $a {1 2 3}
is synonymous with
lindex [lindex [lindex $a 1] 2] 3
Examples
lindex {a b c} => a b c
See Also
[[en:list.n]]
, [[en:lappend.n]]
, [[en:linsert.n]]
, [[en:llength.n]]
, [[en:lsearch.n]]
, [[en:lset.n]]
,
[[en:lsort.n]]
, [[en:lrange.n]]
, [[en:lreplace.n]]
lindex {a b c} {} => a b c
lindex {a b c} 0 => a
lindex {a b c} 2 => c
lindex {a b c} end => c
lindex {a b c} end-1 => b
lindex {{a b c} {d e f} {g h i}} 2 1 => h
lindex {{a b c} {d e f} {g h i}} {2 1} => h
lindex {{{a b} {c d}} {{e f} {g h}}} 1 1 0 => g
lindex {{{a b} {c d}} {{e f} {g h}}} {1 1 0} => g
} text/html} \ -set mime_type text/html \ -set title en:lindex.n \ -set lang en ::xowiki::Page create ::xowiki::page52 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command produces a new list from list by inserting all of the element arguments just before the index’th element 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 has the value end, or if it is greater than or equal to the number of elements in the list, then the new elements are appended to the list. end-integer refers to the last element in the list minus the specified integer offset.
set oldList {the fox jumps over the dog}
set midList [linsert $oldList 1 quick]
set newList [linsert $midList end-1 lazy]
# The old lists still exist though...
set newerList [linsert [linsert $oldList end-1 quick] 1 lazy]
} text/html} \ -set mime_type text/html \ -set title en:linsert.n \ -set lang en ::xowiki::Page create ::xowiki::page53 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command returns a list comprised of all the args, or an empty string if no args are specified. 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.
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}
} text/html} \ -set mime_type text/html \ -set title en:list.n \ -set lang en ::xowiki::Page create ::xowiki::page54 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Treats list as a list and returns a decimal string giving the number of elements in it.
% llength {a b c d e}
5
% llength {a b c}
3
% llength {}
0
Elements are not guaranteed to be exactly words in a dictionary sense of
course, especially when quoting is used: % llength {a b {c d} e}
4
% llength {a b { } c d e}
6
An empty list is not necessarily an empty string: % set var { }; puts "[string length $var],[llength $var]"
1,0
} text/html} \ -set mime_type text/html \ -set title en:llength.n \ -set lang en ::xowiki::Page create ::xowiki::page55 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
load fileName packageName interp
This command loads binary code from a file into the application’s address space and calls an initialization procedure in the package to incorporate it into an interpreter. fileName is the name of the file containing the code; its exact form varies from system to system but on most systems it is a shared library, such as a .so file under Solaris or a DLL under Windows. packageName is the name of the package, and is used to compute the name of an initialization procedure. interp is the path name of the interpreter into which to load the package (see the interp manual entry for details); if interp is omitted, it defaults to the interpreter in which the load command was invoked.
Once the file has been loaded into the application’s address space, one of two initialization procedures will be invoked in the new code. Typically the initialization procedure will add new commands to a Tcl interpreter. The name of the initialization procedure is determined by packageName and whether or not the target interpreter is a safe one. For normal interpreters the name of the initialization procedure will have the form pkg_Init, where pkg is the same as packageName except that the first letter is converted to upper case and all other letters are converted to lower case. For example, if packageName is foo or FOo, the initialization procedure’s name will be Foo_Init.
If the target interpreter is a safe interpreter, then the name of the initialization procedure will be pkg_SafeInit instead of pkg_Init. The pkg_SafeInit function should be written carefully, so that it initializes the safe interpreter only with partial functionality provided by the package that is safe for use by untrusted code. For more information on Safe-Tcl, see the safe manual entry.
The initialization
procedure must match the following prototype:
typedef int Tcl_PackageInitProc(Tcl_Interp *interp);
The interp argument identifies the interpreter in which the package is
to be loaded. The initialization procedure must return TCL_OK or TCL_ERROR
to indicate whether or not it completed successfully; in the event of
an error it should set the interpreter’s result to point to an error message.
The result of the load command will be the result returned by the initialization
procedure.
The actual loading of a file will only be done once for each fileName in an application. If a given fileName is loaded into multiple interpreters, then the first load will load the code and call the initialization procedure; subsequent loads will call the initialization procedure without loading the code again. It is not possible to unload or reload a package.
The load command also supports packages that are statically linked with the application, if those packages have been registered by calling the Tcl_StaticPackage procedure. If fileName is an empty string, then packageName must be specified.
If packageName is omitted or specified as an empty string, Tcl tries to guess the name of the package. This may be done differently on different platforms. The default guess, which is used on most UNIX platforms, is to take the last element of fileName, strip off the first three characters if they are lib, and use any following alphabetic and underline characters as the module name. For example, the command load libxyz4.2.so uses the module name xyz and the command load bin/last.so {} uses the module name last.
If fileName is an empty string, then packageName must be specified. The load command first searches for a statically loaded package (one that has been registered by calling the Tcl_StaticPackage procedure) by that name; if one is found, it is used. Otherwise, the load command searches for a dynamically loaded package by that name, and uses it if it is found. If several different files have been loaded with different versions of the package, Tcl picks the file that was loaded first.
load [file join [pwd] mylib.DLL]
If the same file is loaded by different fileNames, it will be loaded into the process’s address space multiple times. The behavior of this varies from system to system (some systems may detect the redundant loads, others may not).
#include <tcl.h>
When built into a shared/dynamic library with a suitable name (e.g. foo.dll
on Windows, libfoo.so on Solaris and Linux) it can then be loaded into Tcl
with the following:
#include <stdio.h>
static int fooCmd(ClientData clientData,
Tcl_Interp *interp, int objc, char * CONST objv[]) {
printf("called with %d arguments\n", objc);
return TCL_OK;
}
int Foo_Init(Tcl_Interp *interp) {
if (Tcl_InitStubs(interp, "8.1", 0) == NULL) {
return TCL_ERROR;
}
printf("creating foo command");
Tcl_CreateObjCommand(interp, "foo", fooCmd, NULL, NULL);
return TCL_OK;
}
# Now execute the command defined by the extension
# Load the extension
switch $tcl_platform(platform)
{
windows {
load ./foo.dll
}
unix {
load ./libfoo[info sharedlibextension]
}
}
foo
} text/html} \ -set mime_type text/html \ -set title en:load.n \ -set lang en ::xowiki::Page create ::xowiki::page56 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
List must be a valid Tcl list. This command will return a new list consisting of elements first through last, inclusive. First or last may be end (or any abbreviation of it) to refer to the last element of the list. If first is less than zero, it is treated as if it were zero. 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. Note: ‘‘lrange list first first’’ does not always produce the same result as ‘‘lindex list first’’ (although it often does for simple fields that aren’t enclosed in braces); it does, however, produce exactly the same results as ‘‘list [lindex list first]’’
% lrange {a b c d e} 0 1
a b
Selecting the last three elements: % lrange {a b c d e} end-2 end
c d e
Selecting everything except the first and last element: % lrange {a b c d e} 1 end-1
b c d
Selecting a single element with lrange is not the same as doing so with
lindex: % set var {some {elements to} select}
some {elements to} select
% lindex $var 1
elements to
% lrange $var 1 1
{elements to}
} text/html} \ -set mime_type text/html \ -set title en:lrange.n \ -set lang en ::xowiki::Page create ::xowiki::page57 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
lreplace returns a new list formed by replacing one or more elements of list with the element arguments. first and last specify the first and last index of the range of elements to replace. 0 refers to the first element of the list, and end (or any abbreviation of it) may be used to refer to the last element of the list. If list is empty, then first and last are ignored.
If first is less than zero, it is considered to refer to the first element of the list. For non-empty lists, the element indicated by first must exist.
If last is less than zero but greater than first, then any specified elements will be prepended to the list. If last is less than first then no elements are deleted; the new elements are simply inserted before first.
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. If list is empty, any element arguments are added to the end of the list.
% lreplace {a b c d e} 1 1 foo
a foo c d e
Replacing two elements of a list with three: % lreplace {a b c d e} 1 2 three more elements
a three more elements d e
Deleting the last element from a list in a variable: % set var {a b c d e}
a b c d e
% set var [lreplace $var end end]
a b c d
} text/html} \ -set mime_type text/html \ -set title en:lreplace.n \ -set lang en ::xowiki::Page create ::xowiki::page58 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command searches the elements of 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 or -inline 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 it must have one of the following values:
If option is omitted then it defaults to -glob. If more than one of -exact, -glob, -regexp, and -sorted is specified, whichever option is specified last takes precedence. If more than one of -ascii, -dictionary, -integer and -real is specified, the option specified last takes precedence. If more than one of -increasing and -decreasing is specified, the option specified last takes precedence.
lsearch {a b c d e} c => 2
lsearch -all {a b c a b c} c => 2 5
lsearch -inline {a20 b35 c47} b* => b35
lsearch -inline -not {a20 b35 c47} b* => a20
lsearch -all -inline -not {a20 b35 c47} b* => a20 c47
lsearch -all -not {a20 b35 c47} b* => 0 2
lsearch -start 3 {a b c a b c} c => 5
} text/html} \ -set mime_type text/html \ -set title en:lsearch.n \ -set lang en ::xowiki::Page create ::xowiki::page59 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
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. The indices may be presented either consecutively on the command line, or grouped in a Tcl list and presented as a single argument. Finally, it accepts a new value for an element of varName.
If no indices are presented, the command takes
the form:
lset varName newValue
or
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.
If index has the value end, it refers to the last element in the list, and end-integer refers to the last element in the list minus the specified integer offset.
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
or
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.
set x [list [list a b c] [list d e f] [list g h i]]
=> {a b c} {d e f} {g h i}
The indicated return value also becomes the new value of x (except in the
last case, which is an error which leaves the value of x unchanged.) lset x {j k l} => j k l
lset x {} {j k l} => j k l
lset x 0 j => j {d e f} {g h i}
lset x 2 j => {a b c} {d e f} j
lset x end j => {a b c} {d e f} j
lset x end-1 j => {a b c} j {g h i}
lset x 2 1 j => {a b c} {d e f} {g j i}
lset x {2 1} j => {a b c} {d e f} {g j i}
lset x {2 3} j => list index out of range
In the following examples, the initial value of x is: set x [list [list [list a b] [list c d]] \
[list [list e f] [list g h]]]
=> {{a b} {c d}} {{e f} {g h}}
The indicated return value also becomes the new value of x. lset x 1 1 0 j => {{a b} {c d}} {{e f} {j h}}
lset x {1 1 0} j => {{a b} {c d}} {{e f} {j h}}
See Also
[[en:list.n]]
, [[en:lappend.n]]
, [[en:lindex.n]]
, [[en:linsert.n]]
, [[en:llength.n]]
, [[en:lsearch.n]]
,
[[en:lsort.n]]
, [[en:lrange.n]]
, [[en:lreplace.n]]
} text/html} \ -set mime_type text/html \ -set title en:lset.n \ -set lang en ::xowiki::Page create ::xowiki::page60 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command sorts the elements of list, returning a new list in sorted order. The implementation of the lsort command uses the merge-sort algorithm which is a stable sort that has O(n log n) performance characteristics.
By default ASCII sorting is used with the result returned in increasing order. However, any of the following options may be specified before list to control the sorting process (unique abbreviations are accepted):
lsort -integer -index 1 {{First 24} {Second 18} {Third 30}}
returns {Second 18} {First 24} {Third 30}, and
lsort -index end-1 {{a 1 e i} {b 2 3 f g} {c 4 5 6 d h}}
returns {c 4 5 6 d h} {a 1 e i} {b 2 3 f g}. This option is much more efficient than using -command to achieve the same effect.
The options to lsort only control what sort of comparison is used, and do not necessarily constrain what the values themselves actually are. This distinction is only noticeable when the list to be sorted has fewer than two elements.
The lsort command is reentrant, meaning it is safe to use as part of the implementation of a command used in the -command option.
Sorting
a list using ASCII sorting:
% lsort {a10 B2 b1 a1 a2}
Sorting a list using Dictionary sorting:
B2 a1 a10 a2 b1
% lsort -dictionary {a10 B2 b1 a1 a2}
Sorting lists of integers:
a1 a2 a10 b1 B2
% lsort -integer {5 3 1 2 11 4}
Sorting lists of floating-point numbers:
1 2 3 4 5 11
% lsort -integer {1 2 0x5 7 0 4 -1}
-1 0 1 2 4 0x5 7
% lsort -real {5 3 1 2 11 4}
Sorting using indices:
1 2 3 4 5 11
% lsort -real {.5 0.07e1 0.4 6e-1}
0.4 .5 6e-1 0.07e1
% # Note the space character before the c
Stripping duplicate values using sorting:
% lsort {{a 5} { c 3} {b 4} {e 1} {d 2}}
{ c 3} {a 5} {b 4} {d 2} {e 1}
% lsort -index 0 {{a 5} { c 3} {b 4} {e 1} {d 2}}
{a 5} {b 4} { c 3} {d 2} {e 1}
% lsort -index 1 {{a 5} { c 3} {b 4} {e 1} {d 2}}
{e 1} {d 2} { c 3} {b 4} {a 5}
% lsort -unique {a b c a b c a b c}
More complex sorting using a comparison function:
a b c
% proc compare {a b} {
set a0 [lindex $a 0]
set b0 [lindex $b 0]
if {$a0 < $b0} {
return -1
} elseif {$a0 > $b0} {
return 1
}
return [string compare [lindex $a 1] [lindex $b 1]]
}
% lsort -command compare \
{{3 apple} {0x2 carrot} {1 dingo} {2 banana}}
{1 dingo} {2 banana} {0x2 carrot} {3 apple}
} text/html} \ -set mime_type text/html \ -set title en:lsort.n \ -set lang en ::xowiki::Page create ::xowiki::page61 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The memory command gives the Tcl developer control of Tcl’s memory debugging capabilities. The memory command has several suboptions, which are described below. It is only available when Tcl has been compiled with memory debugging enabled (when TCL_MEM_DEBUG is defined at compile time), and after Tcl_InitMemory has been called.
ckalloc 40e478 98 tclProc.c 1406
Calls to ckfree are traced in the same manner.
} text/html} \ -set mime_type text/html \ -set title en:memory.n \ -set lang en ::xowiki::Page create ::xowiki::page62 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
package require msgcat 1.3
::msgcat::mc src-string ?arg arg ...?
::msgcat::mcmax ?src-string src-string ...?
::msgcat::mclocale ?newLocale?
::msgcat::mcpreferences
::msgcat::mcload dirname
::msgcat::mcset locale src-string ?translate-string?
::msgcat::mcmset locale src-trans-list
::msgcat::mcunknown
locale src-string
The msgcat package provides a set of functions that can be used to manage multi-lingual user interfaces. Text strings are defined in a ‘‘message catalog’’ which is independent from the application, and which can be edited or localized without modifying the application source code. New languages or locales are provided by adding a new file to the message catalog.
Use of the message catalog is optional by any application or package, but is encouraged if the application or package wishes to be enabled for multi-lingual applications.
::msgcat::mc will search the messages defined in the current namespace for a translation of src-string; if none is found, it will search in the parent of the current namespace, and so on until it reaches the global namespace. If no translation string exists, ::msgcat::mcunknown is called and the string returned from ::msgcat::mcunknown is returned.
::msgcat::mc is the main function used to localize an application. Instead of using an English string directly, an application can pass the English string through ::msgcat::mc and use the result. If an application is written for a single language in this fashion, then it is easy to add support for additional languages later simply by defining new message catalog entries.
The locale is specified to msgcat by a locale string passed to ::msgcat::mclocale. The locale string consists of a language code, an optional country code, and an optional system-specific code, each separated by ‘‘_’’. The country and language codes are specified in standards ISO-639 and ISO-3166. For example, the locale ‘‘en’’ specifies English and ‘‘en_US’’ specifies U.S. English.
When the msgcat package
is first loaded, the locale is initialized according to the user’s environment.
The variables env(LC_ALL), env(LC_MESSAGES), and env(LANG) are examined
in order. The first of them to have a non-empty value is used to determine
the initial locale. The value is parsed according to the XPG4 pattern
language[_country][.codeset][@modifier]
to extract its parts. The initial locale is then set by calling ::msgcat::mclocale
with the argument
language[_country][_modifier]
On Windows, if none of those environment variables is set, msgcat will
attempt to extract locale information from the registry. If all these attempts
to discover an initial locale from the user’s environment fail, msgcat defaults
to an initial locale of ‘‘C’’.
When a locale is specified by the user, a ‘‘best match’’ search is performed during string translation. For example, if a user specifies en_GB_Funky, the locales ‘‘en_GB_Funky’’, ‘‘en_GB’’, and ‘‘en’’ are searched in order until a matching translation string is found. If no translation string is available, then ::msgcat::unknown is called.
Strings stored in the message catalog are stored relative to the namespace from which they were added. This allows multiple packages to use the same strings without fear of collisions with other packages. It also allows the source string to be shorter and less prone to typographical error.
For example, executing the code
::msgcat::mcset en hello "hello from ::"
will print
namespace eval foo {
::msgcat::mcset en hello "hello from ::foo"
}
puts [::msgcat::mc hello]
namespace eval foo {puts [::msgcat::mc hello]}
hello from ::
When searching for a translation of a message, the message catalog will
search first the current namespace, then the parent of the current namespace,
and so on until the global namespace is reached. This allows child namespaces
to "inherit" messages from their parent namespace.
hello from ::foo
For example, executing
(in the ‘‘en’’ locale) the code
::msgcat::mcset en m1 ":: message1"
will print
::msgcat::mcset en m2 ":: message2"
::msgcat::mcset en m3 ":: message3"
namespace eval ::foo {
::msgcat::mcset en m2 "::foo message2"
::msgcat::mcset en m3 "::foo message3"
}
namespace eval ::foo::bar {
::msgcat::mcset en m3 "::foo::bar message3"
}
namespace import ::msgcat::mc
puts "[mc m1]; [mc m2]; [mc m3]"
namespace eval ::foo {puts "[mc m1]; [mc m2]; [mc m3]"}
namespace eval ::foo::bar {puts "[mc m1]; [mc m2]; [mc m3]"}
:: message1; :: message2; :: message3
Location and Format of Message Files
:: message1; ::foo message2; ::foo message3
:: message1; ::foo message2; ::foo::bar message3
Message files can be located in any directory, subject to the following conditions:
es.msg -- spanish
en_gb.msg -- United Kingdom English
namespace eval ::mypackage {
::msgcat::mcset es "Free Beer!" "Cerveza Gracias!"
}
If a package is installed into a subdirectory of the tcl_pkgPath and loaded via package require, the following procedure is recommended.
# load language files, stored in msgs subdirectory
::msgcat::mcload [file join [file dirname [info script]] msgs]
It is possible that a message
string used as an argument to format might have positionally dependent
parameters that might need to be repositioned. For example, it might be
syntactically desirable to rearrange the sentence structure while translating.
format "We produced %d units in location %s" $num $city
This can be handled by using the positional parameters:
format "In location %s we produced %d units" $city $num
format "We produced %1\$d units in location %2\$s" $num $city
Similarly, positional parameters can be used with scan to extract values
from internationalized strings.
format "In location %2\$s we produced %1\$d units" $num $city
The message catalog code was developed by Mark Harrison.
The namespace command lets you create, access, and destroy separate contexts for commands and variables. See the section WHAT IS A NAMESPACE? below for a brief overview of namespaces. The legal values of option are listed below. Note that you can abbreviate the options.
If namespace has leading namespace qualifiers and any leading namespaces do not exist, they are automatically created.
A
namespace is a collection of commands and variables. It encapsulates the
commands and variables to ensure that they won’t interfere with the commands
and variables of other namespaces. Tcl has always had one such collection,
which we refer to as the global namespace. The global namespace holds all
global variables and commands. The namespace eval command lets you create
new namespaces. For example, proc bump {} {
namespace eval Counter {
creates a new namespace containing the variable num and the procedure bump.
The commands and variables in this namespace are separate from other commands
and variables in the same program. If there is a command named bump in the
global namespace, for example, it will be different from the command bump
in the Counter namespace.
namespace export bump
variable num 0
variable num
incr num
}
}
Namespace variables resemble global variables in Tcl. They exist outside of the procedures in a namespace but can be accessed in a procedure via the variable command, as shown in the example above.
Namespaces are dynamic. You can add and delete commands and variables at
any time, so you can build up the contents of a namespace over time using
a series of namespace eval commands. For example, the following series of
commands has the same effect as the namespace definition shown above:
namespace eval Counter {
Note that the test procedure is added to the Counter namespace, and later
removed via the rename command.
variable num 0
proc bump {} {
variable num
return [incr num]
}
}
namespace eval Counter {
proc test {args} {
return $args
}
}
namespace eval Counter {
rename test ""
}
Namespaces can have other namespaces within them, so they nest hierarchically. A nested namespace is encapsulated inside its parent namespace and can not interfere with other namespaces.
Each namespace has a textual name such as history or ::safe::interp. Since namespaces may nest, qualified names are used to refer to commands, variables, and child namespaces contained inside namespaces. Qualified names are similar to the hierarchical path names for Unix files or Tk widgets, except that :: is used as the separator instead of / or .. The topmost or global namespace has the name ‘‘’’ (i.e., an empty string), although :: is a synonym. As an example, the name ::safe::interp::create refers to the command create in the namespace interp that is a child of namespace ::safe, which in turn is a child of the global namespace, ::.
If you want to access commands
and variables from another namespace, you must use some extra syntax. Names
must be qualified by the namespace that contains them. From the global namespace,
we might access the Counter procedures like this:
Counter::bump 5
We could access the current count like this:
Counter::Reset
puts "count = $Counter::num"
When one namespace contains another, you may need more than one qualifier
to reach its elements. If we had a namespace Foo that contained the namespace
Counter, you could invoke its bump procedure from the global namespace
like this:
Foo::Counter::bump 3
You can also use qualified names when you create and rename commands. For
example, you could add a procedure to the Foo namespace like this:
proc Foo::Test {args} {return $args}
And you could move the same procedure to another namespace like this:
rename Foo::Test Bar::Test
There are a few remaining points about qualified names that we should cover.
Namespaces have nonempty names except for the global namespace. :: is disallowed
in simple command, variable, and namespace names except as a namespace
separator. Extra colons in any separator part of a qualified name are ignored;
i.e. two or more colons are treated as a namespace separator. A trailing ::
in a qualified variable or command name refers to the variable or command
named {}. However, a trailing :: in a qualified namespace name is ignored.
In general, all Tcl commands that take variable and command names support qualified names. This means you can give qualified names to such commands as set, proc, rename, and interp alias. If you provide a fully-qualified name that starts with a ::, there is no question about what command, variable, or namespace you mean. However, if the name does not start with a :: (i.e., is relative), Tcl follows a fixed rule for looking it up: Command and variable names are always resolved by looking first in the current namespace, and then in the global namespace. Namespace names, on the other hand, are always resolved by looking in only the current namespace.
In the following
example, namespace eval Debug {
set traceLevel 0
Tcl looks for traceLevel in the namespace Debug and then in the global
namespace. It looks up the command printTrace in the same way. If a variable
or command name is not found in either context, the name is undefined. To
make this point absolutely clear, consider the following example:
namespace eval Debug {
printTrace $traceLevel
}
set traceLevel 0
Here Tcl looks for traceLevel first in the namespace Foo::Debug. Since it
is not found there, Tcl then looks for it in the global namespace. The
variable Foo::traceLevel is completely ignored during the name resolution
process.
namespace eval Foo {
variable traceLevel 3
printTrace $traceLevel
}
}
You can use the namespace which command to clear up any question
about name resolution. For example, the command:
namespace eval Foo::Debug {namespace which -variable traceLevel}
returns ::traceLevel. On the other hand, the command,
namespace eval Foo {namespace which -variable traceLevel}
returns ::Foo::traceLevel.
As mentioned above, namespace names are looked up differently than the names of variables and commands. Namespace names are always resolved in the current namespace. This means, for example, that a namespace eval command that creates a new namespace always creates a child of the current namespace unless the new namespace name begins with ::.
Tcl has no access control to limit what variables, commands, or namespaces you can reference. If you provide a qualified name that resolves to an element by the name resolution rule above, you can access the element.
You can access a namespace variable from a procedure in the same namespace by using the variable command. Much like the global command, this creates a local link to the namespace variable. If necessary, it also creates the variable in the current namespace and initializes it. Note that the global command only creates links to variables in the global namespace. It is not necessary to use a variable command if you always refer to the namespace variable using an appropriate qualified name.
Namespaces are often
used to represent libraries. Some library commands are used so frequently
that it is a nuisance to type their qualified names. For example, suppose
that all of the commands in a package like BLT are contained in a namespace
called Blt. Then you might access these commands like this:
Blt::graph .g -background red
If you use the graph and table commands frequently, you may want to access
them without the Blt:: prefix. You can do this by importing the commands
into the current namespace, like this:
Blt::table . .g 0,0
namespace import Blt::*
This adds all exported commands from the Blt namespace into the current
namespace context, so you can write code like this:
graph .g -background red
The namespace import command only imports commands from a namespace that
that namespace exported with a namespace export command.
table . .g 0,0
Importing every
command from a namespace is generally a bad idea since you don’t know what
you will get. It is better to import just the specific commands you need.
For example, the command
namespace import Blt::graph Blt::table
imports only the graph and table commands into the current context.
If you
try to import a command that already exists, you will get an error. This
prevents you from importing the same command from two different packages.
But from time to time (perhaps when debugging), you may want to get around
this restriction. You may want to reissue the namespace import command
to pick up new commands that have appeared in a namespace. In that case,
you can use the -force option, and existing commands will be silently overwritten:
namespace import -force Blt::graph Blt::table
If for some reason, you want to stop using the imported commands, you can
remove them with a namespace forget command, like this:
namespace forget Blt::*
This searches the current namespace for any commands imported from Blt.
If it finds any, it removes them. Otherwise, it does nothing. After this,
the Blt commands must be accessed with the Blt:: prefix.
When you delete
a command from the exporting namespace like this:
rename Blt::graph ""
the command is automatically removed from all namespaces that import it.
namespace eval Counter {
namespace export bump reset
variable Num 0
variable Max 100
proc bump {{by 1}} {
variable Num
incr Num $by
Check
return $Num
}
proc reset {} {
variable Num
set Num 0
}
proc Check {} {
variable Num
variable Max
if {$Num > $Max} {
error "too high!"
}
}
}
The procedures bump and reset are exported, so they are included when you
import from the Counter namespace, like this: namespace import Counter::*
However, the Check procedure is not exported, so it is ignored by the import
operation. The namespace import command only imports commands that were declared as exported by their namespace. The namespace export command specifies what commands may be imported by other namespaces. If a namespace import command specifies a command that is not exported, the command is not imported.
namespace eval a {
variable b
proc theTraceCallback { n1 n2 op } {
upvar 1 $n1 var
puts "the value of $n1 has changed to $var"
return
}
trace variable b w [namespace code theTraceCallback]
}
set a::b c
When executed, it prints the message: the value of a::b has changed to c
Examples
Create a namespace containing a variable and an exported command:
namespace eval foo {
variable bar 0
proc grill {} {
variable bar
puts "called [incr bar] times"
}
namespace export grill
}
Call the command defined in the previous example in various ways. # Direct call
foo::grill
# Import into current namespace, then call local alias
namespace import foo::grill
grill
Look up where the command imported in the previous example came from: puts "grill came from [namespace origin grill]"
open fileName
open fileName access
open fileName access permissions
This command opens a file, serial port, or command pipeline and returns a channel identifier that may be used in future invocations of commands like read, puts, and close. If the first character of fileName is not | then the command opens a file: fileName gives the name of the file to open, and it must conform to the conventions described in the filename manual entry.
The access argument, if present, indicates the way in which the file (or command pipeline) is to be accessed. In the first form access may have any of the following values:
In the second form, access consists of a list of any of the following flags, all of which have the standard POSIX meanings. One of the flags must be either RDONLY, WRONLY or RDWR.
If a new file is created as part of opening it, permissions (an integer) is used to set the permissions for the new file in conjunction with the process’s file mode creation mask. Permissions defaults to 0666.
Note that if you are going to be reading or writing binary data from the channel created by this command, you should use the fconfigure command to change the -translation option of the channel to binary before transferring any binary data. This is in contrast to the ‘‘b’’ character passed as part of the equivalent of the access parameter to some versions of the C library fopen() function.
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 id of the spawned process is accessible through the pid command, using the channel id returned by open as argument.
If the command (or one of the commands) executed in the command pipeline returns an error (according to the definition in exec), a Tcl error is generated when close is called on the channel unless the pipeline is in non-blocking mode then no exit status is returned (a silent close with -blocking 0).
It is often useful to use the fileevent command with pipelines so other processing may happen at the same time as running the command in the background.
If fileName refers to a serial port, then the specified serial port is opened and initialized in a platform-dependent manner. Acceptable values for the fileName to use to open a serial port are described in the PORTABILITY ISSUES section.
The fconfigure command can be used to query and set additional configuration options specific to serial ports (where supported):
If type is none then any handshake is switched off. rtscts activates hardware handshake. Hardware handshake signals are described below. For software handshake xonxoff the handshake characters can be redefined with -xchar. An additional hardware handshake dtrdsr is available only under Windows. There is no default handshake configuration, the initial value depends on your operating system settings. The -handshake option cannot be queried.
RS-232 is the most commonly used standard electrical interface for serial communications. A negative voltage (-3V..-12V) define a mark (on=1) bit and a positive voltage (+3..+12V) define a space (off=0) bit (RS-232C). The following signals are specified for incoming and outgoing data, status lines and handshaking. Here we are using the terms workstation for your computer and modem for the external device, because some signal names (DCD, RI) come from modems. Of course your external device may use these signal lines for other purposes.
A lot of different errors may occur during serial read operations or during event polling in background. The external device may have been switched off, the data lines may be noisy, system buffers may overrun or your mode settings may be wrong. That’s why a reliable software should always catch serial read operations. In cases of an error Tcl returns a general file I/O error. Then fconfigure -lasterror may help to locate the problem. The following error codes may be returned.
When running Tcl interactively, there may be some strange interactions between the real console, if one is present, and a command pipeline that uses standard input or output. If a command pipeline is opened for reading from a 32-bit application, some of the keystrokes entered at the console will be sent to the command pipeline and some will be sent to the Tcl evaluator. If a command pipeline is opened for writing to a 32-bit application, no output is visible on the console until the pipe is closed. These problems only occur because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input or output, but is redirected from or to a file, then the above problems do not occur.
Whether or not Tcl is running interactively, if a command pipeline is opened for reading from a 16-bit DOS application, the call to open will not return until end-of-file has been received from the command pipeline’s standard output. If a command pipeline is opened for writing to a 16-bit DOS application, no data will be sent to the command pipeline’s standard output until the pipe is actually closed. This problem occurs because 16-bit DOS applications are run synchronously, as described above.
Opening a command pipeline is not supported under Macintosh, since applications do not support the concept of standard input or output.
When running Tcl interactively, there may be some strange interactions between the console, if one is present, and a command pipeline that uses standard input. If a command pipeline is opened for reading, some of the lines entered at the console will be sent to the command pipeline and some will be sent to the Tcl evaluator. This problem only occurs because both Tcl and the child application are competing for the console at the same time. If the command pipeline is started from a script, so that Tcl is not accessing the console, or if the command pipeline does not use standard input, but is redirected from a file, then the above problem does not occur.
See the PORTABILITY ISSUES section of the exec command for additional information not specific to command pipelines about executing applications on the various platforms
set fl [open "| ls this_file_does_not_exist"]
set data [read $fl]
if {[catch {close $fl} err]} {
puts "ls command failed: $err"
}
package forget ?package package ...? package ifneeded package version ?script? package names package present ?-exact? package ?version? package provide package ?version? package require ?-exact? package ?version? package unknown ?command? package vcompare version1 version2 package versions package package vsatisfies version1 version2
This command keeps a simple database of the packages available for use by the current interpreter and how to load them into the interpreter. It supports multiple versions of each package and arranges for the correct version of a package to be loaded based on what is needed by the application. This command also detects and reports version clashes. Typically, only the package require and package provide commands are invoked in normal Tcl scripts; the other commands are used primarily by system scripts that maintain the package database.
The behavior of the package command is determined by its first argument. The following forms are permitted:
Version numbers consist of one or more decimal numbers separated by dots, such as 2 or 1.162 or 3.1.13.1. The first number is called the major version number. Larger numbers correspond to later versions of a package, with leftmost numbers having greater significance. For example, version 2.1 is later than 1.3 and version 3.4.6 is later than 3.3.5. Missing fields are equivalent to zeroes: version 1.3 is the same as version 1.3.0 and 1.3.0.0, so it is earlier than 1.3.1 or 1.3.0.2. A later version number is assumed to be upwards compatible with an earlier version number as long as both versions have the same major version number. For example, Tcl scripts written for version 2.3 of a package should work unchanged under versions 2.3.2, 2.4, and 2.5.1. Changes in the major version number signify incompatible changes: if code is written to use version 2.1 of a package, it is not guaranteed to work unmodified with either version 1.7.3 or version 3.1.
The recommended way to use packages in Tcl is to invoke package require and package provide commands in scripts, and use the procedure pkg_mkIndex to create package index files. Once you’ve done this, packages will be loaded automatically in response to package require commands. See the documentation for pkg_mkIndex for details.
package require Tk
package require http
To test to see if the Snack package is available and load if it is (often
useful for optional enhancements to programs where the loss of the functionality
is not critical) do this: if {[catch {package require Snack}]} {
# We have the package, configure the app to use it
} else {
# Set up a dummy interface to work around the absence
}
} text/html} \ -set mime_type text/html \ -set title en:package.n \ -set lang en ::xowiki::Page create ::xowiki::page66 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:parray.n \ -set lang en ::xowiki::Page create ::xowiki::page67 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]} text/html} \ -set mime_type text/html \ -set title en:pid.n \ -set lang en ::xowiki::Page create ::xowiki::page68 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
pid - Retrieve process identifiersSynopsis
pid ?fileId?
Description
If the fileId argument is given then it should normally refer to a process pipeline created with the open command. In this case the pid command will return a list whose elements are the process identifiers of all the processes in the pipeline, in order. The list will be empty if fileId refers to an open file that isn’t a process pipeline. If no fileId argument is given then pid returns the process identifier of the current process. All process identifiers are returned as decimal strings.
Example
Print process information about the processes in a pipeline using the SysV ps program before reading the output of that pipeline:
set pipeline [open "| zcat somefile.gz | grep foobar | sort -u"]
# Print process information
exec ps -fp [pid $pipeline] >@stdout
# Print a separator and then the output of the pipeline
puts [string repeat - 70]
puts [read $pipeline]
close $pipeline
See Also
[[en:exec.n]] , [[en:open.n]]
Keywords
file, pipeline, process identifier
::pkg::create is a utility procedure that is part of the standard Tcl library. It is used to create an appropriate package ifneeded command for a given package specification. It can be used to construct a pkgIndex.tcl file for use with the package mechanism.
At least one -load or -source parameter must be given.
} text/html} \ -set mime_type text/html \ -set title en:pkg::create.n \ -set lang en ::xowiki::Page create ::xowiki::page69 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
pkg_mkIndex ?-direct? ?-lazy? ?-load pkgPat? ?-verbose? dir ?pattern pattern ...?
Pkg_mkIndex is a utility procedure that is part of the standard Tcl library. It is used to create index files that allow packages to be loaded automatically when package require commands are executed. To use pkg_mkIndex, follow these steps:
The package management facilities overlap somewhat with the auto-loader, in that both arrange for files to be loaded on-demand. However, package management is a higher-level mechanism that uses the auto-loader for the last step in the loading process. It is generally better to index a package with pkg_mkIndex rather than auto_mkindex because the package mechanism provides version control: several versions of a package can be made available in the index files, with different applications using different versions based on package require commands. In contrast, auto_mkindex does not understand versions so it can only handle a single version of each package. It is probably not a good idea to index a given package with both pkg_mkIndex and auto_mkindex. If you use pkg_mkIndex to index a package, its commands cannot be invoked until package require has been used to select a version; in contrast, packages indexed with auto_mkindex can be used immediately since there is no version control.
Pkg_mkIndex depends on the package unknown command, the package ifneeded command, and the auto-loader. The first time a package require command is invoked, the package unknown script is invoked. This is set by Tcl initialization to a script that evaluates all of the pkgIndex.tcl files in the auto_path. The pkgIndex.tcl files contain package ifneeded commands for each version of each available package; these commands invoke package provide commands to announce the availability of the package, and they setup auto-loader information to load the files of the package. If the -lazy flag was provided when the pkgIndex.tcl was generated, a given file of a given version of a given package isn’t actually loaded until the first time one of its commands is invoked. Thus, after invoking package require you may not see the package’s commands in the interpreter, but you will be able to invoke the commands and they will be auto-loaded.
Some packages, for instance packages which use namespaces and export commands or those which require special initialization, might select that their package files be loaded immediately upon package require instead of delaying the actual loading to the first use of one of the package’s command. This is the default mode when generating the package index. It can be overridden by specifying the -lazy argument.
If each script or file contains one package, and packages are only contained in one file, then things are easy. You simply specify all files to be indexed in any order with some glob patterns.
In general, it is OK for scripts to have dependencies on other packages. If scripts contain package require commands, these are stubbed out in the interpreter used to process the scripts, so these do not cause problems. If scripts call into other packages in global code, these calls are handled by a stub unknown command. However, if scripts make variable references to other package’s variables in global code, these will cause errors. That is also bad coding style.
If binary files have dependencies on other packages, things can become tricky because it is not possible to stub out C-level APIs such as Tcl_PkgRequire API when loading a binary file. For example, suppose the BLT package requires Tk, and expresses this with a call to Tcl_PkgRequire in its Blt_Init routine. To support this, you must run pkg_mkIndex in an interpreter that has Tk loaded. You can achieve this with the -load pkgPat option. If you specify this option, pkg_mkIndex will load any packages listed by info loaded and that match pkgPat into the interpreter used to process files. In most cases this will satisfy the Tcl_PkgRequire calls made by binary files.
If you are indexing two binary files and one depends on the other, you should specify the one that has dependencies last. This way the one without dependencies will get loaded and indexed, and then the package it provides will be available when the second file is processed. You may also need to load the first package into the temporary interpreter used to create the index by using the -load flag; it won’t hurt to specify package patterns that are not yet loaded.
If you have a package that is split across scripts and a binary file, then you should avoid the -load flag. The problem is that if you load a package before computing the index it masks any other files that provide part of the same package. If you must use -load, then you must specify the scripts first; otherwise the package loaded from the binary file may mask the package defined by the scripts.
args body
The proc command creates a new Tcl procedure named name, replacing any existing command or procedure there may have been by that name. Whenever the new command is invoked, the contents of body will be executed by the Tcl interpreter. Normally, name is unqualified (does not include the names of any containing namespaces), and the new procedure is created in the current namespace. If name includes any namespace qualifiers, the procedure is created in the specified namespace. Args specifies the formal arguments to the procedure. It consists of a list, possibly empty, each of whose elements specifies one argument. Each argument specifier is also a list with either one or two fields. If there is only a single field in the specifier then it is the name of the argument; if there are two fields, then the first is the argument name and the second is its default value.
When name 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 the formal arguments that don’t have defaults, and there must not be any extra actual arguments. There is one special case to permit procedures with variable numbers of arguments. If the last formal argument has the name args, then a call to the procedure may contain more actual arguments than the procedure has formals. In this case, all of the actual arguments starting at the one that would be assigned to args are combined into a list (as if the list command had been used); this combined value is assigned to the local variable args.
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 only be accessed by invoking the global command or the upvar command. Namespace variables can only be accessed by invoking the variable command or the upvar command.
The proc command returns an empty string. 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.
proc printArguments args {
foreach arg $args {
puts $arg
}
}
This procedure is a bit like the incr command, except it multiplies the
contents of the named variable by the value, which defaults to 2: proc mult {varName {multiplier 2}} {
upvar 1 $varName var
set var [expr {$var * $multiplier}]
}
} text/html} \ -set mime_type text/html \ -set title en:proc.n \ -set lang en ::xowiki::Page create ::xowiki::page71 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Writes the characters given by string to the channel given by channelId.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdout or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension. The channel must have been opened for output.
If no channelId 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.
Newline characters in the output are translated by puts to platform-specific end-of-line sequences according to the current value of the -translation option for the channel (for example, on PCs newlines are normally replaced with carriage-return-linefeed sequences; on Macintoshes newlines are normally replaced with carriage-returns). See the fconfigure manual entry for a discussion on ways in which fconfigure will alter output.
Tcl buffers output internally, so characters written with puts may not appear immediately on the output file or device; Tcl will normally delay output until the buffer is full or the channel is closed. You can force output to appear immediately with the flush command.
When the output buffer fills up, the puts command will normally block until all the buffered data has been accepted for output by the operating system. If channelId is in nonblocking mode then the puts command will not block even if the operating system cannot accept the data. Instead, Tcl continues to buffer the data and writes it in the background as fast as the underlying file or device can accept it. The application must use the Tcl event loop for nonblocking output to work; otherwise Tcl never finds out that the file or device is ready for more output data. It is possible for an arbitrarily large amount of data to be buffered for a channel in nonblocking mode, which could consume a large amount of memory. To avoid wasting memory, nonblocking I/O should normally be used in an event-driven fashion with the fileevent command (don’t invoke puts unless you have recently been notified via a file event that the channel is ready for more output data).
puts "Hello, World!"
Print a message in several parts: puts -nonewline "Hello, "
puts "World!"
Print a message to the standard error channel: puts stderr "Hello, World!"
Append a log message to a file: set chan [open my.log a]
set timestamp [clock format [clock seconds]]
puts $chan "$timestamp - Hello, World!"
close $chan
} text/html} \ -set mime_type text/html \ -set title en:puts.n \ -set lang en ::xowiki::Page create ::xowiki::page72 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Returns the absolute path name of the current working directory.
set tarFile [file normalize somefile.tar]
set savedDir [pwd]
cd /tmp
exec tar -xf $tarFile
cd $savedDir
} text/html} \ -set mime_type text/html \ -set title en:pwd.n \ -set lang en ::xowiki::Page create ::xowiki::page73 -noinit \ -set description {} \ -set nls_language en_US \ -set text {\[\[en:#toc\]\]
\n\n
\ \n
\nA\ regular\ expression\ describes\ strings\ of\ characters.\ It&rsquo\;s\ a\npattern\ that\ matches\ certain\ strings\ and\ doesn&rsquo\;t\ match\ others.\ \n
\ \n
\nThis\ manual\ page\ primarily\ describes\nAREs.\ \ BREs\ mostly\ exist\ for\ backward\ compatibility\ in\ some\ old\ programs\;\nthey\ will\ be\ discussed\ at\ the\ end.\ \ POSIX\ EREs\ are\ almost\ an\ exact\ subset\nof\ AREs.\ \ Features\ of\ AREs\ that\ are\ not\ present\ in\ EREs\ will\ be\ indicated.\n\n
\ \n
\nTcl\ regular\ expressions\ are\ implemented\ using\nthe\ package\ written\ by\ Henry\ Spencer,\ based\ on\ the\ 1003.2\ spec\ and\ some\n(not\ quite\ all)\ of\ the\ Perl5\ extensions\ (thanks,\ Henry!).\ \ Much\ of\ the\ description\nof\ regular\ expressions\ below\ is\ copied\ verbatim\ from\ his\ manual\ entry.\
\nAn\nARE\ is\ one\ or\ more\ branches,\ separated\ by\ &lsquo\;|&rsquo\;,\ matching\ anything\ that\ matches\nany\ of\ the\ branches.\
\nA\ branch\ is\ zero\ or\ more\ constraints\ or\ quantified\natoms,\ concatenated.\ It\ matches\ a\ match\ for\ the\ first,\ followed\ by\ a\ match\nfor\ the\ second,\ etc\;\ an\ empty\ branch\ matches\ the\ empty\ string.\
\nA\ quantified\natom\ is\ an\ atom\ possibly\ followed\ by\ a\ single\ quantifier.\ Without\ a\ quantifier,\nit\ matches\ a\ match\ for\ the\ atom.\ The\ quantifiers,\ and\ what\ a\ so-quantified\natom\ matches,\ are:\
\n\n\n\n
\n- *\
\n- a\ sequence\ of\ 0\ or\ more\ matches\ of\ the\ atom\
\n\n- +\
\n- a\ sequence\nof\ 1\ or\ more\ matches\ of\ the\ atom\
\n\n- ?\
\n- a\ sequence\ of\ 0\ or\ 1\ matches\ of\ the\natom\
\n\n- \{m\}\
\n- a\ sequence\ of\ exactly\ m\ matches\ of\ the\ atom\
\n\n- \{m,\}\
\n- a\ sequence\ of\nm\ or\ more\ matches\ of\ the\ atom\
\n\n- \{m,n\}\
\n- a\ sequence\ of\ m\ through\ n\ (inclusive)\nmatches\ of\ the\ atom\;\ m\ may\ not\ exceed\ n\
\n\n- *?\ \ +?\ \ ??\ \ \{m\}?\ \ \{m,\}?\ \ \{m,n\}?\n
\n- non-greedy\ quantifiers,\ which\ match\ the\ same\ possibilities,\ but\ prefer\ the\nsmallest\ number\ rather\ than\ the\ largest\ number\ of\ matches\ (see\ MATCHING)\n
\n
\nThe\ forms\ using\ \{\ and\ \}\ are\ known\ as\ bounds.\ The\ numbers\ m\ and\ n\ are\ unsigned\ndecimal\ integers\ with\ permissible\ values\ from\ 0\ to\ 255\ inclusive.\
\nAn\ atom\nis\ one\ of:\
\n\n\n\n
\n- (re)\
\n- (where\ re\ is\ any\ regular\ expression)\ matches\ a\ match\ for\nre,\ with\ the\ match\ noted\ for\ possible\ reporting\
\n\n- (?:re)\
\n- as\ previous,\ but\ndoes\ no\ reporting\ (a\ &lsquo\;&lsquo\;non-capturing&rsquo\;&rsquo\;\ set\ of\ parentheses)\
\n\n- ()\
\n- matches\ an\ empty\nstring,\ noted\ for\ possible\ reporting\
\n\n- (?:)\
\n- matches\ an\ empty\ string,\ without\nreporting\
\n\n- \[chars\]\
\n- a\ bracket\ expression,\ matching\ any\ one\ of\ the\ chars\ (see\nBRACKET\ EXPRESSIONS\ for\ more\ detail)\
\n\n
\n- \ .\
\n- matches\ any\ single\ character\
\n\n- \\k\
\n- (where\ k\ is\ a\ non-alphanumeric\ character)\nmatches\ that\ character\ taken\ as\ an\ ordinary\ character,\ e.g.\ \\\\\ matches\ a\ backslash\ncharacter\
\n\n- \\c\
\n- where\ c\ is\ alphanumeric\ (possibly\ followed\ by\ other\ characters),\nan\ escape\ (AREs\ only),\ see\ ESCAPES\ below\
\n\n- \{\
\n- when\ followed\ by\ a\ character\nother\ than\ a\ digit,\ matches\ the\ left-brace\ character\ &lsquo\;\{&rsquo\;\;\ when\ followed\ by\na\ digit,\ it\ is\ the\ beginning\ of\ a\ bound\ (see\ above)\
\n\n- x\
\n- where\ x\ is\ a\ single\ncharacter\ with\ no\ other\ significance,\ matches\ that\ character.\
\n
\nA\ constraint\nmatches\ an\ empty\ string\ when\ specific\ conditions\ are\ met.\ A\ constraint\ may\nnot\ be\ followed\ by\ a\ quantifier.\ The\ simple\ constraints\ are\ as\ follows\;\nsome\ more\ constraints\ are\ described\ later,\ under\ ESCAPES.\
\n\n\n\n
\nmatches\ at\ any\ point\ where\ no\ substring\nmatching\ re\ begins\- ^\
\n- matches\ at\ the\nbeginning\ of\ a\ line\
\n\n- \$\
\n- matches\ at\ the\ end\ of\ a\ line\
\n\n- (?=re)\
\n- positive\ lookahead\n(AREs\ only),\ matches\ at\ any\ point\ where\ a\ substring\ matching\ re\ begins\n
\n\n- (?!re)\
\n- negative\ lookahead\ (AREs\ only),\
\n
\nThe\ lookahead\ constraints\ may\ not\ contain\ back\ references\n(see\ later),\ and\ all\ parentheses\ within\ them\ are\ considered\ non-capturing.\n
\nAn\ RE\ may\ not\ end\ with\ &lsquo\;\\&rsquo\;.\ \n
\ \n
\nIf\ two\ characters\nin\ the\ list\ are\ separated\ by\ &lsquo\;-&rsquo\;,\ this\ is\ shorthand\ for\ the\ full\ range\ of\ncharacters\ between\ those\ two\ (inclusive)\ in\ the\ collating\ sequence,\ e.g.\n\[0-9\]\ in\ ASCII\ matches\ any\ decimal\ digit.\ Two\ ranges\ may\ not\ share\ an\ endpoint,\nso\ e.g.\ a-c-e\ is\ illegal.\ Ranges\ are\ very\ collating-sequence-dependent,\ and\ portable\nprograms\ should\ avoid\ relying\ on\ them.\
\nTo\ include\ a\ literal\ \]\ or\ -\ in\ the\nlist,\ the\ simplest\ method\ is\ to\ enclose\ it\ in\ \[.\ and\ .\]\ to\ make\ it\ a\ collating\nelement\ (see\ below).\ Alternatively,\ make\ it\ the\ first\ character\ (following\na\ possible\ &lsquo\;^&rsquo\;),\ or\ (AREs\ only)\ precede\ it\ with\ &lsquo\;\\&rsquo\;.\ Alternatively,\ for\ &lsquo\;-&rsquo\;,\ make\nit\ the\ last\ character,\ or\ the\ second\ endpoint\ of\ a\ range.\ To\ use\ a\ literal\n-\ as\ the\ first\ endpoint\ of\ a\ range,\ make\ it\ a\ collating\ element\ or\ (AREs\nonly)\ precede\ it\ with\ &lsquo\;\\&rsquo\;.\ With\ the\ exception\ of\ these,\ some\ combinations\ using\n\[\ (see\ next\ paragraphs),\ and\ escapes,\ all\ other\ special\ characters\ lose\ntheir\ special\ significance\ within\ a\ bracket\ expression.\
\nWithin\ a\ bracket\nexpression,\ a\ collating\ element\ (a\ character,\ a\ multi-character\ sequence\nthat\ collates\ as\ if\ it\ were\ a\ single\ character,\ or\ a\ collating-sequence\nname\ for\ either)\ enclosed\ in\ \[.\ and\ .\]\ stands\ for\ the\ sequence\ of\ characters\nof\ that\ collating\ element.\ The\ sequence\ is\ a\ single\ element\ of\ the\ bracket\nexpression&rsquo\;s\ list.\ A\ bracket\ expression\ in\ a\ locale\ that\ has\ multi-character\ncollating\ elements\ can\ thus\ match\ more\ than\ one\ character.\ So\ (insidiously),\na\ bracket\ expression\ that\ starts\ with\ ^\ can\ match\ multi-character\ collating\nelements\ even\ if\ none\ of\ them\ appear\ in\ the\ bracket\ expression!\ (Note:\nTcl\ currently\ has\ no\ multi-character\ collating\ elements.\ This\ information\nis\ only\ for\ illustration.)\
\nFor\ example,\ assume\ the\ collating\ sequence\ includes\na\ ch\ multi-character\ collating\ element.\ Then\ the\ RE\ \[\[.ch.\]\]*c\ (zero\ or\ more\nch&rsquo\;s\ followed\ by\ c)\ matches\ the\ first\ five\ characters\ of\ &lsquo\;chchcc&rsquo\;.\ Also,\ the\nRE\ \[^c\]b\ matches\ all\ of\ &lsquo\;chb&rsquo\;\ (because\ \[^c\]\ matches\ the\ multi-character\ ch).\n
\nWithin\ a\ bracket\ expression,\ a\ collating\ element\ enclosed\ in\ \[=\ and\ =\]\nis\ an\ equivalence\ class,\ standing\ for\ the\ sequences\ of\ characters\ of\ all\ncollating\ elements\ equivalent\ to\ that\ one,\ including\ itself.\ (If\ there\ are\nno\ other\ equivalent\ collating\ elements,\ the\ treatment\ is\ as\ if\ the\ enclosing\ndelimiters\ were\ &lsquo\;\[.&rsquo\;\ and\ &lsquo\;.\]&rsquo\;.)\ For\ example,\ if\ o\ and\ o&rsquo\;o^&rsquo\;\ are\ the\ members\ of\ an\nequivalence\ class,\ then\ &lsquo\;\[\[=o=\]\]&rsquo\;,\ &lsquo\;\[\[=o&rsquo\;o^&rsquo\;=\]\]&rsquo\;,\ and\ &lsquo\;\[oo&rsquo\;o^&rsquo\;\]&rsquo\;\ are\ all\ synonymous.\nAn\ equivalence\ class\ may\ not\ be\ an\ endpoint\ of\ a\ range.\ (Note:\ \ Tcl\ currently\nimplements\ only\ the\ Unicode\ locale.\ It\ doesn&rsquo\;t\ define\ any\ equivalence\ classes.\nThe\ examples\ above\ are\ just\ illustrations.)\
\nWithin\ a\ bracket\ expression,\nthe\ name\ of\ a\ character\ class\ enclosed\ in\ \[:\ and\ :\]\ stands\ for\ the\ list\nof\ all\ characters\ (not\ all\ collating\ elements!)\ belonging\ to\ that\ class.\nStandard\ character\ classes\ are:\
\n
\\n
\nalpha\  \;\  \;A\ letter.\ \nupper\  \;\  \;An\ upper-case\ letter.\ \nlower\  \;\  \;A\ lower-case\ letter.\ \ndigit\  \;\  \;A\ decimal\ digit.\ \nxdigit\  \;\  \;A\ hexadecimal\ digit.\ \nalnum\  \;\  \;An\ alphanumeric\ (letter\ or\ digit).\ \nprint\  \;\  \;An\ alphanumeric\ (same\ as\ alnum).\nblank\  \;\  \;A\ space\ or\ tab\ character.\nspace\  \;\  \;A\ character\ producing\ white\ space\ in\ displayed\ text.\ \npunct\  \;\  \;A\ punctuation\ character.\ \ngraph\  \;\  \;A\ character\ with\ a\ visible\ representation.\ \ncntrl\  \;\  \;A\ control\ character.\ \n
\nA\ locale\ may\ provide\ others.\ (Note\ that\ the\ current\ Tcl\ implementation\ has\nonly\ one\ locale:\ the\ Unicode\ locale.)\ A\ character\ class\ may\ not\ be\ used\nas\ an\ endpoint\ of\ a\ range.\
\nThere\ are\ two\ special\ cases\ of\ bracket\ expressions:\nthe\ bracket\ expressions\ \[\[:<\;:\]\]\ and\ \[\[:>\;:\]\]\ are\ constraints,\ matching\ empty\nstrings\ at\ the\ beginning\ and\ end\ of\ a\ word\ respectively.\ \ A\ word\ is\ defined\nas\ a\ sequence\ of\ word\ characters\ that\ is\ neither\ preceded\ nor\ followed\nby\ word\ characters.\ A\ word\ character\ is\ an\ alnum\ character\ or\ an\ underscore\n(_).\ These\ special\ bracket\ expressions\ are\ deprecated\;\ users\ of\ AREs\ should\nuse\ constraint\ escapes\ instead\ (see\ below).\ \n
\nCharacter-entry\ escapes\ (AREs\ only)\ exist\ to\ make\nit\ easier\ to\ specify\ non-printing\ and\ otherwise\ inconvenient\ characters\nin\ REs:\
\n\n\n\n
\nthe\ character\ whose\ octal\ value\ is\ 0xyz\n- \\a\
\n- alert\ (bell)\ character,\ as\ in\ C\
\n\n- \\b\
\n- backspace,\ as\ in\ C\
\n\n- \\B\
\n- synonym\nfor\ \\\ to\ help\ reduce\ backslash\ doubling\ in\ some\ applications\ where\ there\nare\ multiple\ levels\ of\ backslash\ processing\
\n\n- \\cX\
\n- (where\ X\ is\ any\ character)\nthe\ character\ whose\ low-order\ 5\ bits\ are\ the\ same\ as\ those\ of\ X,\ and\ whose\nother\ bits\ are\ all\ zero\
\n\n- \\e\
\n- the\ character\ whose\ collating-sequence\ name\ is\n&lsquo\;ESC&rsquo\;,\ or\ failing\ that,\ the\ character\ with\ octal\ value\ 033\
\n\n- \\f\
\n- formfeed,\ as\nin\ C\
\n\n- \\n\
\n- newline,\ as\ in\ C\
\n\n- \\r\
\n- carriage\ return,\ as\ in\ C\
\n\n- \\t\
\n- horizontal\ tab,\ as\nin\ C\
\n\n- \\uwxyz\
\n- (where\ wxyz\ is\ exactly\ four\ hexadecimal\ digits)\ the\ Unicode\ncharacter\ U+wxyz\ in\ the\ local\ byte\ ordering\
\n\n- \\Ustuvwxyz\
\n- (where\ stuvwxyz\ is\nexactly\ eight\ hexadecimal\ digits)\ reserved\ for\ a\ somewhat-hypothetical\ Unicode\nextension\ to\ 32\ bits\
\n\n- \\v\
\n- vertical\ tab,\ as\ in\ C\ are\ all\ available.\
\n\n- \\xhhh\
\n- (where\nhhh\ is\ any\ sequence\ of\ hexadecimal\ digits)\ the\ character\ whose\ hexadecimal\nvalue\ is\ 0xhhh\ (a\ single\ character\ no\ matter\ how\ many\ hexadecimal\ digits\nare\ used).\
\n\n- \\0\
\n- the\ character\ whose\ value\ is\ 0\
\n\n- \\xy\
\n- (where\ xy\ is\ exactly\ two\noctal\ digits,\ and\ is\ not\ a\ back\ reference\ (see\ below))\ the\ character\ whose\noctal\ value\ is\ 0xy\
\n\n- \\xyz\
\n- (where\ xyz\ is\ exactly\ three\ octal\ digits,\ and\ is\nnot\ a\ back\ reference\ (see\ below))\
\n
\nHexadecimal\ digits\ are\ &lsquo\;0&rsquo\;-&lsquo\;9&rsquo\;,\ &lsquo\;a&rsquo\;-&lsquo\;f&rsquo\;,\ and\ &lsquo\;A&rsquo\;-&lsquo\;F&rsquo\;.\ Octal\ digits\ are\ &lsquo\;0&rsquo\;-&lsquo\;7&rsquo\;.\
\nThe\ character-entry\nescapes\ are\ always\ taken\ as\ ordinary\ characters.\ For\ example,\ \\135\ is\ \]\ in\nASCII,\ but\ \\135\ does\ not\ terminate\ a\ bracket\ expression.\ Beware,\ however,\nthat\ some\ applications\ (e.g.,\ C\ compilers)\ interpret\ \ such\ sequences\ themselves\nbefore\ the\ regular-expression\ package\ gets\ to\ see\ them,\ which\ may\ require\ndoubling\ (quadrupling,\ etc.)\ the\ &lsquo\;\\&rsquo\;.\
\nClass-shorthand\ escapes\ (AREs\ only)\ provide\nshorthands\ for\ certain\ commonly-used\ character\ classes:\
\n\n\n\n
\n- \\d\
\n- \[\[:digit:\]\]\
\n\n- \\s\n
\n- \[\[:space:\]\]\
\n\n- \\w\
\n- \[\[:alnum:\]_\]\ (note\ underscore)\
\n\n- \\D\
\n- \[^\[:digit:\]\]\
\n\n- \\S\
\n- \[^\[:space:\]\]\n
\n\n- \\W\
\n- \[^\[:alnum:\]_\]\ (note\ underscore)\
\n
\nWithin\ bracket\ expressions,\ &lsquo\;\\d&rsquo\;,\ &lsquo\;\\s&rsquo\;,\ and\n&lsquo\;\\w&rsquo\;\ lose\ their\ outer\ brackets,\ and\ &lsquo\;\\D&rsquo\;,\ &lsquo\;\\S&rsquo\;,\ and\ &lsquo\;\\W&rsquo\;\ are\ illegal.\ (So,\ for\ example,\n\[a-c\\d\]\ is\ equivalent\ to\ \[a-c\[:digit:\]\].\ Also,\ \[a-c\\D\],\ which\ is\ equivalent\ to\n\[a-c^\[:digit:\]\],\ is\ illegal.)\
\nA\ constraint\ escape\ (AREs\ only)\ is\ a\ constraint,\nmatching\ the\ empty\ string\ if\ specific\ conditions\ are\ met,\ written\ as\ an\nescape:\
\n\n\n\n
\nsee\ below\- \\A\
\n- matches\ only\ at\ the\ beginning\ of\ the\ string\ (see\ MATCHING,\ below,\nfor\ how\ this\ differs\ from\ &lsquo\;^&rsquo\;)\
\n\n- \\m\
\n- matches\ only\ at\ the\ beginning\ of\ a\ word\
\n\n- \\M\n
\n- matches\ only\ at\ the\ end\ of\ a\ word\
\n\n- \\y\
\n- matches\ only\ at\ the\ beginning\ or\ end\nof\ a\ word\
\n\n- \\Y\
\n- matches\ only\ at\ a\ point\ that\ is\ not\ the\ beginning\ or\ end\ of\na\ word\
\n\n- \\Z\
\n- matches\ only\ at\ the\ end\ of\ the\ string\ (see\ MATCHING,\ below,\ for\nhow\ this\ differs\ from\ &lsquo\;\$&rsquo\;)\
\n\n- \\m\
\n- (where\ m\ is\ a\ nonzero\ digit)\ a\ back\ reference,\nsee\ below\
\n\n- \\mnn\
\n- (where\ m\ is\ a\ nonzero\ digit,\ and\ nn\ is\ some\ more\ digits,\nand\ the\ decimal\ value\ mnn\ is\ not\ greater\ than\ the\ number\ of\ closing\ capturing\nparentheses\ seen\ so\ far)\ a\ back\ reference,\
\n
\nA\ word\ is\ defined\nas\ in\ the\ specification\ of\ \[\[:<\;:\]\]\ and\ \[\[:>\;:\]\]\ above.\ Constraint\ escapes\ are\nillegal\ within\ bracket\ expressions.\
\nA\ back\ reference\ (AREs\ only)\ matches\nthe\ same\ string\ matched\ by\ the\ parenthesized\ subexpression\ specified\ by\nthe\ number,\ so\ that\ (e.g.)\ (\[bc\])\\1\ matches\ bb\ or\ cc\ but\ not\ &lsquo\;bc&rsquo\;.\ The\ subexpression\nmust\ entirely\ precede\ the\ back\ reference\ in\ the\ RE.\ Subexpressions\ are\ numbered\nin\ the\ order\ of\ their\ leading\ parentheses.\ Non-capturing\ parentheses\ do\ not\ndefine\ subexpressions.\
\nThere\ is\ an\ inherent\ historical\ ambiguity\ between\noctal\ character-entry\ \ escapes\ and\ back\ references,\ which\ is\ resolved\ by\nheuristics,\ as\ hinted\ at\ above.\ A\ leading\ zero\ always\ indicates\ an\ octal\nescape.\ A\ single\ non-zero\ digit,\ not\ followed\ by\ another\ digit,\ is\ always\ntaken\ as\ a\ back\ reference.\ A\ multi-digit\ sequence\ not\ starting\ with\ a\ zero\nis\ taken\ as\ a\ back\ \ reference\ if\ it\ comes\ after\ a\ suitable\ subexpression\n(i.e.\ the\ number\ is\ in\ the\ legal\ range\ for\ a\ back\ reference),\ and\ otherwise\nis\ taken\ as\ octal.\ \n
\nNormally\ the\ flavor\ of\ RE\ being\ used\ is\ specified\ by\ application-dependent\nmeans.\ However,\ this\ can\ be\ overridden\ by\ a\ director.\ If\ an\ RE\ of\ any\ flavor\nbegins\ with\ &lsquo\;***:&rsquo\;,\ the\ rest\ of\ the\ RE\ is\ an\ ARE.\ If\ an\ RE\ of\ any\ flavor\ begins\nwith\ &lsquo\;***=&rsquo\;,\ the\ rest\ of\ the\ RE\ is\ taken\ to\ be\ a\ literal\ string,\ with\ all\ncharacters\ considered\ ordinary\ characters.\
\nAn\ ARE\ may\ begin\ with\ embedded\noptions:\ a\ sequence\ (?xyz)\ (where\ xyz\ is\ one\ or\ more\ alphabetic\ characters)\nspecifies\ options\ affecting\ the\ rest\ of\ the\ RE.\ These\ supplement,\ and\ can\noverride,\ any\ options\ specified\ by\ the\ application.\ The\ available\ option\nletters\ are:\
\n\n\n\n
\n- b\
\n- rest\ of\ RE\ is\ a\ BRE\
\n\n- c\
\n- case-sensitive\ matching\ (usual\ default)\n
\n\n- e\
\n- rest\ of\ RE\ is\ an\ ERE\
\n\n- i\
\n- case-insensitive\ matching\ (see\ MATCHING,\ below)\n
\n\n- m\
\n- historical\ synonym\ for\ n\
\n\n- n\
\n- newline-sensitive\ matching\ (see\ MATCHING,\ below)\n
\n\n- p\
\n- partial\ newline-sensitive\ matching\ (see\ MATCHING,\ below)\
\n\n- q\
\n- rest\ of\ RE\nis\ a\ literal\ (&lsquo\;&lsquo\;quoted&rsquo\;&rsquo\;)\ string,\ all\ ordinary\ characters\
\n\n- s\
\n- non-newline-sensitive\nmatching\ (usual\ default)\
\n\n- t\
\n- tight\ syntax\ (usual\ default\;\ see\ below)\
\n\n- w\
\n- inverse\npartial\ newline-sensitive\ (&lsquo\;&lsquo\;weird&rsquo\;&rsquo\;)\ matching\ (see\ MATCHING,\ below)\
\n\n- x\
\n- expanded\nsyntax\ (see\ below)\
\n
\nEmbedded\ options\ take\ effect\ at\ the\ )\ terminating\ the\nsequence.\ They\ are\ available\ only\ at\ the\ start\ of\ an\ ARE,\ and\ may\ not\ be\nused\ later\ within\ it.\
\nIn\ addition\ to\ the\ usual\ (tight)\ RE\ syntax,\ in\ which\nall\ characters\ are\ significant,\ there\ is\ an\ expanded\ syntax,\ available\nin\ all\ flavors\ of\ RE\ with\ the\ -expanded\ switch,\ or\ in\ AREs\ with\ the\ embedded\nx\ option.\ In\ the\ expanded\ syntax,\ white-space\ characters\ are\ ignored\ and\nall\ characters\ between\ a\ #\ and\ the\ following\ newline\ (or\ the\ end\ of\ the\nRE)\ are\ ignored,\ permitting\ paragraphing\ and\ commenting\ a\ complex\ RE.\ There\nare\ three\ exceptions\ to\ that\ basic\ rule:\
\n\na\ white-space\ character\ or\ &lsquo\;#&rsquo\;\ preceded\nby\ &lsquo\;\\&rsquo\;\ is\ retained\
\nwhite\ space\ or\ &lsquo\;#&rsquo\;\ within\ a\ bracket\ expression\ is\ retained\n
\nwhite\ space\ and\ comments\ are\ illegal\ within\ multi-character\ symbols\ like\nthe\ ARE\ &lsquo\;(?:&rsquo\;\ or\ the\ BRE\ &lsquo\;\\(&rsquo\;\
\nExpanded-syntax\ white-space\ characters\ are\ blank,\ntab,\ newline,\ and\ any\ character\ that\ belongs\ to\ the\ space\ character\ class.\n
\nFinally,\ in\ an\ ARE,\ outside\ bracket\ expressions,\ the\ sequence\ &lsquo\;(?#ttt)&rsquo\;\ (where\nttt\ is\ any\ text\ not\ containing\ a\ &lsquo\;)&rsquo\;)\ is\ a\ comment,\ completely\ ignored.\ Again,\nthis\ is\ not\ allowed\ between\ the\ characters\ of\ multi-character\ symbols\ like\n&lsquo\;(?:&rsquo\;.\ Such\ comments\ are\ more\ a\ historical\ artifact\ than\ a\ useful\ facility,\nand\ their\ use\ is\ deprecated\;\ use\ the\ expanded\ syntax\ instead.\
\nNone\ of\ these\nmetasyntax\ extensions\ is\ available\ if\ the\ application\ (or\ an\ initial\ ***=\ndirector)\ has\ specified\ that\ the\ user&rsquo\;s\ input\ be\ treated\ as\ a\ literal\ string\nrather\ than\ as\ an\ RE.\ \n
\nMost\ atoms,\ and\ all\ constraints,\ have\ no\ preference.\nA\ parenthesized\ RE\ has\ the\ same\ preference\ (possibly\ none)\ as\ the\ RE.\ A\nquantified\ atom\ with\ quantifier\ \{m\}\ or\ \{m\}?\ has\ the\ same\ preference\ (possibly\nnone)\ as\ the\ atom\ itself.\ A\ quantified\ atom\ with\ other\ normal\ quantifiers\n(including\ \{m,n\}\ with\ m\ equal\ to\ n)\ prefers\ longest\ match.\ A\ quantified\natom\ with\ other\ non-greedy\ quantifiers\ (including\ \{m,n\}?\ with\ m\ equal\ to\nn)\ prefers\ shortest\ match.\ A\ branch\ has\ the\ same\ preference\ as\ the\ first\nquantified\ atom\ in\ it\ which\ has\ a\ preference.\ An\ RE\ consisting\ of\ two\ or\nmore\ branches\ connected\ by\ the\ |\ operator\ prefers\ longest\ match.\
\nSubject\nto\ the\ constraints\ imposed\ by\ the\ rules\ for\ matching\ the\ whole\ RE,\ subexpressions\nalso\ match\ the\ longest\ or\ shortest\ possible\ substrings,\ based\ on\ their\npreferences,\ with\ subexpressions\ starting\ earlier\ in\ the\ RE\ taking\ priority\nover\ ones\ starting\ later.\ Note\ that\ outer\ subexpressions\ thus\ take\ priority\nover\ their\ component\ subexpressions.\
\nNote\ that\ the\ quantifiers\ \{1,1\}\ and\n\{1,1\}?\ can\ be\ used\ to\ force\ longest\ and\ shortest\ preference,\ respectively,\non\ a\ subexpression\ or\ a\ whole\ RE.\
\nMatch\ lengths\ are\ measured\ in\ characters,\nnot\ collating\ elements.\ An\ empty\ string\ is\ considered\ longer\ than\ no\ match\nat\ all.\ For\ example,\ bb*\ matches\ the\ three\ middle\ characters\ of\ &lsquo\;abbbc&rsquo\;,\ (week|wee)(night|knights)\nmatches\ all\ ten\ characters\ of\ &lsquo\;weeknights&rsquo\;,\ when\ (.*).*\ is\ matched\ against\nabc\ the\ parenthesized\ subexpression\ matches\ all\ three\ characters,\ and\ when\n(a*)*\ is\ matched\ against\ bc\ both\ the\ whole\ RE\ and\ the\ parenthesized\ subexpression\nmatch\ an\ empty\ string.\
\nIf\ case-independent\ matching\ is\ specified,\ the\ effect\nis\ much\ as\ if\ all\ case\ distinctions\ had\ vanished\ from\ the\ alphabet.\ When\nan\ alphabetic\ that\ exists\ in\ multiple\ cases\ appears\ as\ an\ ordinary\ character\noutside\ a\ bracket\ expression,\ it\ is\ effectively\ transformed\ into\ a\ bracket\nexpression\ containing\ both\ cases,\ so\ that\ x\ becomes\ &lsquo\;\[xX\]&rsquo\;.\ When\ it\ appears\ninside\ a\ bracket\ expression,\ all\ case\ counterparts\ of\ it\ are\ added\ to\ the\nbracket\ expression,\ so\ that\ \[x\]\ becomes\ \[xX\]\ and\ \[^x\]\ becomes\ &lsquo\;\[^xX\]&rsquo\;.\
\nIf\ newline-sensitive\nmatching\ is\ specified,\ .\ and\ bracket\ expressions\ using\ ^\ will\ never\ match\nthe\ newline\ character\ (so\ that\ matches\ will\ never\ cross\ newlines\ unless\nthe\ RE\ explicitly\ arranges\ it)\ and\ ^\ and\ \$\ will\ match\ the\ empty\ string\ after\nand\ before\ a\ newline\ respectively,\ in\ addition\ to\ matching\ at\ beginning\nand\ end\ of\ string\ respectively.\ ARE\ \\A\ and\ \\Z\ continue\ to\ match\ beginning\nor\ end\ of\ string\ only.\
\nIf\ partial\ newline-sensitive\ matching\ is\ specified,\nthis\ affects\ .\ and\ bracket\ expressions\ as\ with\ newline-sensitive\ matching,\nbut\ not\ ^\ and\ &lsquo\;\$&rsquo\;.\
\nIf\ inverse\ partial\ newline-sensitive\ matching\ is\ specified,\nthis\ affects\ ^\ and\ \$\ as\ with\ newline-sensitive\ matching,\ but\ not\ .\ and\ bracket\nexpressions.\ This\ isn&rsquo\;t\ very\ useful\ but\ is\ provided\ for\ symmetry.\ \n
\nThe\ only\nfeature\ of\ AREs\ that\ is\ actually\ incompatible\ with\ POSIX\ EREs\ is\ that\ \\\ndoes\ not\ lose\ its\ special\ significance\ inside\ bracket\ expressions.\ All\ other\nARE\ features\ use\ syntax\ which\ is\ illegal\ or\ has\ undefined\ or\ unspecified\neffects\ in\ POSIX\ EREs\;\ the\ ***\ syntax\ of\ directors\ likewise\ is\ outside\nthe\ POSIX\ syntax\ for\ both\ BREs\ and\ EREs.\
\nMany\ of\ the\ ARE\ extensions\ are\nborrowed\ from\ Perl,\ but\ some\ have\ been\ changed\ to\ clean\ them\ up,\ and\ a\nfew\ Perl\ extensions\ are\ not\ present.\ Incompatibilities\ of\ note\ include\ &lsquo\;\\b&rsquo\;,\n&lsquo\;\\B&rsquo\;,\ the\ lack\ of\ special\ treatment\ for\ a\ trailing\ newline,\ the\ addition\ of\ncomplemented\ bracket\ expressions\ to\ the\ things\ affected\ by\ newline-sensitive\nmatching,\ the\ restrictions\ on\ parentheses\ and\ back\ references\ in\ lookahead\nconstraints,\ and\ the\ longest/shortest-match\ (rather\ than\ first-match)\ matching\nsemantics.\
\nThe\ matching\ rules\ for\ REs\ containing\ both\ normal\ and\ non-greedy\nquantifiers\ have\ changed\ since\ early\ beta-test\ versions\ of\ this\ package.\n(The\ new\ rules\ are\ much\ simpler\ and\ cleaner,\ but\ don&rsquo\;t\ work\ as\ hard\ at\ guessing\nthe\ user&rsquo\;s\ real\ intentions.)\
\nHenry\ Spencer&rsquo\;s\ original\ 1986\ regexp\ package,\nstill\ in\ widespread\ use\ (e.g.,\ in\ pre-8.1\ releases\ of\ Tcl),\ implemented\ an\nearly\ version\ of\ today&rsquo\;s\ EREs.\ There\ are\ four\ incompatibilities\ between\ regexp&rsquo\;s\nnear-EREs\ (&lsquo\;RREs&rsquo\;\ for\ short)\ and\ AREs.\ In\ roughly\ increasing\ order\ of\ significance:\n
\n
In\ AREs,\ \\\ followed\ by\ an\ alphanumeric\ character\ is\ either\ an\ escape\ or\nan\ error,\ while\ in\ RREs,\ it\ was\ just\ another\ way\ of\ writing\ the\ \ alphanumeric.\nThis\ should\ not\ be\ a\ problem\ because\ there\ was\ no\ reason\ to\ write\ such\na\ sequence\ in\ RREs.\\n\n\n\{\ followed\ by\ a\ digit\ in\ an\ ARE\ is\ the\ beginning\ of\na\ bound,\ while\ in\ RREs,\ \{\ was\ always\ an\ ordinary\ character.\ Such\ sequences\nshould\ be\ rare,\ and\ will\ often\ result\ in\ an\ error\ because\ following\ characters\nwill\ not\ look\ like\ a\ valid\ bound.\
\nIn\ AREs,\ \\\ remains\ a\ special\ character\nwithin\ &lsquo\;\[\]&rsquo\;,\ so\ a\ literal\ \\\ within\ \[\]\ must\ be\ written\ &lsquo\;\\\\&rsquo\;.\ \\\\\ also\ gives\ a\ literal\n\\\ within\ \[\]\ in\ RREs,\ but\ only\ truly\ paranoid\ programmers\ routinely\ doubled\nthe\ backslash.\
\nAREs\ report\ the\ longest/shortest\ match\ for\ the\ RE,\ rather\nthan\ the\ first\ found\ in\ a\ specified\ search\ order.\ This\ may\ affect\ some\ RREs\nwhich\ were\ written\ in\ the\ expectation\ that\ the\ first\ match\ would\ be\ reported.\n(The\ careful\ crafting\ of\ RREs\ to\ optimize\ the\ search\ order\ for\ fast\ matching\nis\ obsolete\ (AREs\ examine\ all\ possible\ matches\ in\ parallel,\ and\ their\ performance\nis\ largely\ insensitive\ to\ their\ complexity)\ but\ cases\ where\ the\ search\norder\ was\ exploited\ to\ deliberately\ \ find\ a\ match\ which\ was\ not\ the\ longest/shortest\nwill\ need\ rewriting.)\
\ \n
\ \n
\ \n
\n\n
\n
read channelId numChars
In the first form, the read command reads all of the data from channelId up to the end of the file. 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 characters to read. Exactly that many characters will be read and returned, unless there are fewer than numChars left in the file; in this case all the remaining characters are returned. If the channel is configured to use a multi-byte encoding, then the number of characters read may not be the same as the number of bytes read.
ChannelId must be an identifier for an open channel such as the Tcl standard input channel (stdin), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension. The channel must have been opened for input.
If channelId is in nonblocking mode, the command may not read as many characters as requested: once all available input has been read, the command will return the data that is available rather than blocking for more input. If the channel is configured to use a multi-byte encoding, then there may actually be some bytes remaining in the internal buffers that do not form a complete character. These bytes will not be returned until a complete character is available or end-of-file is reached. The -nonewline switch is ignored if the command returns before reaching the end of the file.
Read translates end-of-line sequences in the input into newline characters according to the -translation option for the channel. See the fconfigure manual entry for a discussion on ways in which fconfigure will alter input.
For most applications a channel connected to a serial port should be configured to be nonblocking: fconfigure channelId -blocking 0. Then read behaves much like described above. Care must be taken when using read on blocking serial ports:
set fl [open /proc/meminfo]
set data [read $fl]
close $fl
set lines [split $data \n]
} text/html} \ -set mime_type text/html \ -set title en:read.n \ -set lang en ::xowiki::Page create ::xowiki::page75 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
string
Determines whether the regular expression exp matches part or all of string and returns 1 if it does, 0 if it doesn’t, unless -inline is specified (see below). (Regular expression matching is described in the re_syntax reference page.)
If additional arguments are specified after string then they are treated as the names of variables in which 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.
If the initial arguments to regexp start with - then they are treated as switches. The following switches are currently supported:
regexp -inline -- {\w(\w)} " inlined "
=> {in n}
regexp -all -inline -- {\w(\w)} " inlined "
=> {in n li i ne e}
If there are more subMatchVar’s 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.
regexp {\<foo(?!bar\>)(\w*)} $string -> restOfWord
Note that the whole matched substring has been placed in the variable ->
which is a name chosen to look nice given that we are not actually interested
in its contents.
Find the index of the word badger (in any case) within
a string and store that in the variable location:
regexp -indices {(?i)\<badger\>} $string location
Count the number of octal digits in a string:
regexp -all {[0-7]} $string
List all words (consisting of all sequences of non-whitespace characters)
in a string:
regexp -all -inline {\S+} $string
} text/html} \ -set mime_type text/html \ -set title en:regexp.n \ -set lang en ::xowiki::Page create ::xowiki::page76 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
package require registry 1.1
registry option keyName ?arg arg ...?
The registry package provides a general set of operations for manipulating the Windows registry. The package implements the registry Tcl command. This command is only supported on the Windows platform. Warning: this command should be used with caution as a corrupted registry can leave your system in an unusable state.
KeyName is the name of a registry key. Registry keys must be one of the following forms:
Hostname specifies the name of any valid Windows host that exports its registry. The rootname component must be one of HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CLASSES_ROOT, HKEY_CURRENT_USER, HKEY_CURRENT_CONFIG, HKEY_PERFORMANCE_DATA, or HKEY_DYN_DATA. The keypath can be one or more registry key names separated by backslash (\) characters.
Option indicates what to do with the registry key name. Any unique abbreviation for option is acceptable. The valid options are:
set regPath {HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment}
set curPath [registry get $regPath "Path"]
registry set $regPath "Path" "$curPath;$addPath"
registry broadcast "Environment"
In addition to the symbolically named types listed above, unknown types are identified using a 32-bit integer that corresponds to the type code returned by the system interfaces. In this case, the data is represented exactly in Tcl, including any embedded nulls.
package require registry
set ext .tcl
# Read the type name
set type [registry get HKEY_CLASSES_ROOT\\$ext {}]
# Work out where to look for the command
set path HKEY_CLASSES_ROOT\\$type\\Shell\\Open\\command
# Read the command!
set command [registry get $path {}]
puts "$ext opens with $command"
} text/html} \ -set mime_type text/html \ -set title en:registry.n \ -set lang en ::xowiki::Page create ::xowiki::page77 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command matches the regular expression exp against string, and either copies string to the variable whose name is given by varName or returns string if varName is not present. (Regular expression matching is described in the re_syntax reference page.) If there is a match, then while copying string to varName (or to the result of this command if varName is not present) 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.
If the initial arguments to regsub start with - then they are treated as switches. The following switches are currently supported:
If varName is supplied, the command returns a count of the number of matching ranges that were found and replaced, otherwise the string after replacement is returned. See the manual entry for regexp for details on the interpretation of regular expressions.
regsub -all {\<foo\>} $string bar string
Insert double-quotes around the first instance of the word interesting,
however it is capitalised. regsub -nocase {\<interesting\>} $string {"&"} string
Convert all non-ASCII and Tcl-significant characters into \u escape sequences
by using regsub and subst in combination: # This RE is just a character class for everything "bad"
set RE {[][{}\$\s\u0100-\uffff]}
# We will substitute with a fragment of Tcl script in brackets
set substitution {[format \\\\u%04x [scan "\\&" %c]]}
# Now we apply the substitution to get a subst-string that
# will perform the computational parts of the conversion.
set quoted [subst [regsub -all $RE $string $substitution]]
} text/html} \ -set mime_type text/html \ -set title en:regsub.n \ -set lang en ::xowiki::Page create ::xowiki::page78 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
oldName newName
Rename the command that used to be called oldName so that it is now called newName. If newName is an empty string then oldName is deleted. oldName and newName may include namespace qualifiers (names of containing namespaces). If a command is renamed into a different namespace, future invocations of it will execute in the new namespace. The rename command returns an empty string as result.
rename ::source ::theRealSource
set sourceCount 0
proc ::source args {
global sourceCount
puts "called source for the [incr sourceCount]’th time"
uplevel 1 ::theRealSource $args
}
} text/html} \ -set mime_type text/html \ -set title en:rename.n \ -set lang en ::xowiki::Page create ::xowiki::page79 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The resource command provides some generic operations for dealing with Macintosh resources. This command is only supported on the Macintosh platform. Each Macintosh file consists of two forks: a data fork and a resource fork. You use the normal open, puts, close, etc. commands to manipulate the data fork. You must use this command, however, to interact with the resource fork. Option indicates what resource command to perform. Any unique abbreviation for option is acceptable. The valid options are:
} text/html} \ -set mime_type text/html \ -set title en:resource.n \ -set lang en ::xowiki::Page create ::xowiki::page80 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Return immediately from the current procedure (or top-level command or source command), with string as the return value. If string is not specified then an empty string will be returned as result.
In addition to the result of a procedure, the return code of a procedure may also be set by return through use of the -code option. In the usual case where the -code option isn’t specified the procedure will return normally. However, the -code option may be used to generate an exceptional return from the procedure. Code may have any of the following values:
The -code option is rarely used. It is provided so that procedures that implement new control structures can reflect exceptional conditions back to their callers.
Two additional options, -errorinfo and -errorcode, may be used to provide additional information during error returns. These options are ignored unless code is error.
The -errorinfo option specifies an initial stack trace for the errorInfo variable; if it is not specified then the stack trace left in errorInfo will include the call to the procedure and higher levels on the stack but it will not include any information about the context of the error within the procedure. Typically the info value is supplied from the value left in errorInfo after a catch command trapped an error within the procedure.
If the -errorcode option is specified then code provides a value for the errorCode variable. If the option is not specified then errorCode will default to NONE.
proc printOneLine {} {
puts "line 1" ;# This line will be printed.
return
puts "line 2" ;# This line will not be printed.
}
Next, an example of using return to set the value returned by the procedure.
proc returnX {} {return X}
puts [returnX] ;# prints "X"
Next, a more complete example, using return -code error to report invalid
arguments. proc factorial {n} {
if {![string is integer $n] || ($n < 0)} {
return -code error \
"expected non-negative integer,\
but got \"$n\""
}
if {$n < 2} {
return 1
}
set m [expr {$n - 1}]
set code [catch {factorial $m} factor]
if {$code != 0} {
return -code $code $factor
}
set product [expr {$n * $factor}]
if {$product < 0} {
return -code error \
"overflow computing factorial of $n"
}
return $product
}
Next, a procedure replacement for break. proc myBreak {} {
return -code break
}
} text/html} \ -set mime_type text/html \ -set title en:return.n \ -set lang en ::xowiki::Page create ::xowiki::page81 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
::safe::interpInit slave ?options...?
::safe::interpConfigure slave ?options...?
::safe::interpDelete slave
::safe::interpAddToAccessPath slave directory
::safe::interpFindInAccessPath slave directory
::safe::setLogCmd ?cmd arg...?
?-accessPath pathList? ?-statics boolean? ?-noStatics? ?-nested boolean? ?-nestedLoadOk? ?-deleteHook script?
The Safe Base ensures that untrusted Tcl scripts cannot harm the hosting application. The Safe Base prevents integrity and privacy attacks. Untrusted Tcl scripts are prevented from corrupting the state of the hosting application or computer. Untrusted scripts are also prevented from disclosing information stored on the hosting computer or in the hosting application to any party.
The Safe Base allows a master interpreter to create safe, restricted interpreters that contain a set of predefined aliases for the source, load, file, encoding, and exit commands and are able to use the auto-loading and package mechanisms.
No knowledge of the file system structure is leaked to the safe interpreter, because it has access only to a virtualized path containing tokens. When the safe interpreter requests to source a file, it uses the token in the virtual path as part of the file name to source; the master interpreter transparently translates the token into a real directory name and executes the requested operation (see the section SECURITY below for details). Different levels of security can be selected by using the optional flags of the commands described below.
All commands provided in the master interpreter by the Safe Base reside in the safe namespace:
# Create a new interp with the same configuration as "$i0" :
set i1 [eval safe::interpCreate [safe::interpConfigure $i0]]
# Get the current deleteHook
set dh [safe::interpConfigure $i0 -del]
# Change (only) the statics loading ok attribute of an interp
# and its deleteHook (leaving the rest unchanged) :
safe::interpConfigure $i0 -delete {foo bar} -statics 0 ;
$slave eval [list set tk_library [::safe::interpFindInAccessPath $name $tk_library]]
$slave eval [list set tk_library [::safe::interpAddToAccessPath $name $tk_library]]
Example of use:
::safe::setLogCmd puts stderr
Below is the output of a sample session in which a safe interpreter attempted to source a file not found in its virtual access path. Note that the safe interpreter only received an error message saying that the file was not found:
NOTICE for slave interp10 : Created
NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=()
NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)}
ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory
The commands available in a safe interpreter, in addition to the safe set as defined in interp manual page, are mediated aliases for source, load, exit, and safe subsets of file and encoding. The safe interpreter can also auto-load code and it can request that packages be loaded.
Because some of these commands access the local file system, there is a potential for information leakage about its directory structure. To prevent this, commands that take file names as arguments in a safe interpreter use tokens instead of the real directory names. These tokens are translated to the real directory name while a request to, e.g., source a file is mediated by the master interpreter. This virtual path system is maintained in the master interpreter for each safe interpreter created by ::safe::interpCreate or initialized by ::safe::interpInit and the path maps tokens accessible in the safe interpreter into real path names on the local file system thus preventing safe interpreters from gaining knowledge about the structure of the file system of the host on which the interpreter is executing. The only valid file names arguments for the source and load aliases provided to the slave are path in the form of [file join token filename] (i.e. when using the native file path formats: token/filename on Unix, token\filename on Windows, and token:filename on the Mac), where token is representing one of the directories of the accessPath list and filename is one file in that directory (no sub directories access are allowed).
When a token is used in a safe interpreter in a request to source or load a file, the token is checked and translated to a real path name and the file to be sourced or loaded is located on the file system. The safe interpreter never gains knowledge of the actual path name under which the file is stored on the file system.
To further prevent potential information leakage from sensitive files that are accidentally included in the set of files that can be sourced by a safe interpreter, the source alias restricts access to files meeting the following constraints: the file name must fourteen characters or shorter, must not contain more than one dot ("."), must end up with the extension .tcl or be called tclIndex.
Each element of the initial access path list will be assigned a token that will be set in the slave auto_path and the first element of that list will be set as the tcl_library for that slave.
If the access path argument is not given or is the empty list, the default behavior is to let the slave access the same packages as the master has access to (Or to be more precise: only packages written in Tcl (which by definition can’t be dangerous as they run in the slave interpreter) and C extensions that provides a Safe_Init entry point). For that purpose, the master’s auto_path will be used to construct the slave access path. In order that the slave successfully loads the Tcl library files (which includes the auto-loading mechanism itself) the tcl_library will be added or moved to the first position if necessary, in the slave access path, so the slave tcl_library will be the same as the master’s (its real path will still be invisible to the slave though). In order that auto-loading works the same for the slave and the master in this by default case, the first-level sub directories of each directory in the master auto_path will also be added (if not already included) to the slave access path. You can always specify a more restrictive path for which sub directories will never be searched by explicitly specifying your directory list with the -accessPath flag instead of relying on this default mechanism.
When the accessPath is changed after the first creation or initialization (i.e. through interpConfigure -accessPath list), an auto_reset is automatically evaluated in the safe interpreter to synchronize its auto_index with the new token list.
} text/html} \ -set mime_type text/html \ -set title en:SafeBase.n \ -set lang en ::xowiki::Page create ::xowiki::page82 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command parses fields from an input string in the same fashion as the ANSI C sscanf procedure and returns a count of the number of conversions performed, or -1 if the end of the input string is reached before any conversions have been performed. String gives the input to be parsed and format indicates how to parse it, using % conversion specifiers as in sscanf. 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 variable. If no varName variables are specified, then scan works in an inline manner, returning the data that would otherwise be stored in the variables as a list. In the inline case, an empty string is returned when the end of the input string is reached before any conversions have been performed.
Scan operates by scanning string and format together. If the next character in format is a blank or tab then it matches any number of white space characters in string (including zero). Otherwise, if it isn’t a % character then it must match the next character of string. When a % is encountered in format, it indicates the start of a conversion specifier. A conversion specifier contains up to four fields after the %: a *, which indicates that the converted value is to be discarded instead of assigned to a variable; a XPG3 position specifier; a number indicating a maximum field width; a field size modifier; and a conversion character. All of these fields are optional except for the conversion character. The fields that are present must appear in the order given above.
When scan finds a conversion specifier in format, it first skips any white-space characters in string (unless the specifier is [ or c). Then it converts the next input characters according to the conversion specifier and stores the result in the variable given by the next argument to scan.
If the % is followed by a decimal number and a $, as in ‘‘%2$d’’, then the variable to use is not taken from the next sequential argument. Instead, it is taken from the argument indicated by the number, where 1 corresponds to the first varName. If there are any positional specifiers in format then all of the specifiers must be positional. Every varName on the argument list must correspond to exactly one conversion specifier or an error is generated, or in the inline case, any position can be specified at most once and the empty positions will be filled in with empty strings.
The following conversion characters are supported:
The number of characters read from the input for a conversion is the largest number that makes sense for that particular conversion (e.g. as many decimal digits as possible for %d, as many octal digits as possible for %o, and so on). The input field for a given conversion terminates either when a white-space character is encountered or when the maximum field width has been reached, whichever comes first. If a * is present in the conversion specifier then no variable is assigned and the next scan argument is not consumed.
The behavior of the scan command is the same as the behavior of the ANSI C sscanf procedure except for the following differences:
set string "#08D03F"
scan $string "#%2x%2x%2x" r g b
Parse a HH:MM time string, noting that this avoids problems with octal
numbers by forcing interpretation as decimals (if we did not care, we would
use the %i conversion instead): set string "08:08" ;# *Not* octal!
if {[scan $string "%d:%d" hours minutes] != 2} {
error "not a valid time string"
}
# We have to understand numeric ranges ourselves...
if {$minutes < 0 || $minutes > 59} {
error "invalid number of minutes"
}
Break a string up into sequences of non-whitespace characters (note the
use of the %n conversion so that we get skipping over leading whitespace
correct): set string " a string {with braced words} + leading space "
set words {}
while {[scan $string %s%n word length] == 2} {
lappend words $word
set string [string range $string $length end]
}
Parse a simple coordinate string, checking that it is complete by looking
for the terminating character explicitly: set string "(5.2,-4e-2)"
# Note that the spaces before the literal parts of
# the scan pattern are significant, and that ")" is
# the Unicode character \u0029
if {
[scan $string " (%f ,%f %c" x y last] != 3
|| $last != 0x0029
} then {
error "invalid coordinate string"
}
puts "X=$x, Y=$y"
Changes the current access position for channelId.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
The offset and origin arguments specify the position at which the next read or write will occur for channelId. Offset must be an integer (which may be negative) and origin must be one of the following:
The origin argument defaults to start.
The command flushes all buffered output for the channel before the command returns, even if the channel is in nonblocking mode. It also discards any buffered and unread input. This command returns an empty string. An error occurs if this command is applied to channels whose underlying file or device does not support seeking.
Note that offset values are byte offsets, not character offsets. Both seek and tell operate in terms of bytes, not characters, unlike read.
set f [open file.txt]
set data1 [read $f]
seek $f 0
set data2 [read $f]
close $f
# $data1 == $data2 if the file wasn’t updated
Read the last 10 bytes from a file: set f [open file.data]
# This is guaranteed to work with binary data but
# may fail with other encodings...
fconfigure $f -translation binary
seek $f -10 end
set data [read $f 10]
close $f
} text/html} \ -set mime_type text/html \ -set title en:seek.n \ -set lang en ::xowiki::Page create ::xowiki::page84 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Returns the value of variable varName. If value is specified, then set the value of varName to value, creating a new variable if one doesn’t already exist, and return its value. If varName contains an open parenthesis and ends with a close parenthesis, then it refers to an array element: the characters before the first open parenthesis are the name of the array, and the characters between the parentheses are the index within the array. Otherwise varName refers to a scalar variable.
If varName includes namespace qualifiers (in the array name if it refers to an array element), or if varName is unqualified (does not include the names of any containing namespaces) but no procedure is active, varName refers to a namespace variable resolved according to the rules described under NAME RESOLUTION in the namespace manual page.
If a procedure is active and varName is unqualified, then varName refers to a parameter or local variable of the procedure, unless varName was declared to resolve differently through one of the global, variable or upvar commands.
set r [expr rand()]
Store a short message in an array element: set anAry(msg) "Hello, World!"
Store a short message in an array element specified by a variable: set elemName "msg"
set anAry($elemName) "Hello, World!"
Copy a value into the variable out from a variable whose name is stored
in the vbl (note that it is often easier to use arrays in practice instead
of doing double-dereferencing): set in0 "small random"
set in1 "large random"
set vbl in[expr {rand() >= 0.5}]
set out [set $vbl]
} text/html} \ -set mime_type text/html \ -set title en:set.n \ -set lang en ::xowiki::Page create ::xowiki::page85 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
socket ?options? host port
socket -server command ?options? port
This command opens a network socket and returns a channel identifier that may be used in future invocations of commands like read, puts and flush. At present only the TCP network protocol is supported; future releases may include support for additional protocols. The socket command may be used to open either the client or server side of a connection, depending on whether the -server switch is specified.
Note that the default encoding for all sockets is the system encoding, as returned by encoding system. Most of the time, you will need to use fconfigure to alter this to something else, such as utf-8 (ideal for communicating with other Tcl processes) or iso8859-1 (useful for many network protocols, especially the older ones).
If the -server option is not specified, then the client side of a connection is opened and the command returns a channel identifier that can be used for both reading and writing. Port and host specify a port to connect to; there must be a server accepting connections on this port. Port is an integer port number (or service name, where supported and understood by the host operating system) and host is either a domain-style name such as www.tcl.tk or a numerical IP address such as 127.0.0.1. Use localhost to refer to the host on which the command is invoked.
The following options may also be present before host to specify additional information about the connection:
If the -server option is specified then the new socket will be a server for the port given by port (either an integer or a service name, where supported and understood by the host operating system; if port is zero, the operating system will allocate a free port to the server socket which may be discovered by using fconfigure to read the -sockname option). Tcl will automatically accept connections to the given port. For each connection Tcl will create a new channel that may be used to communicate with the client. Tcl then invokes command with three additional arguments: the name of the new channel, the address, in network address notation, of the client’s host, and the client’s port number.
The following additional option may also be specified before host:
Server channels cannot be used for input or output; their sole use is to accept new client connections. The channels created for each incoming client connection are opened for input and output. Closing the server channel shuts down the server so that no new connections will be accepted; however, existing connections will be unaffected.
Server sockets depend on the Tcl event mechanism to find out when new connections are opened. If the application doesn’t enter the event loop, for example by invoking the vwait command or calling the C procedure Tcl_DoOneEvent, then no connections will be accepted.
If port is specified as zero, the operating system will allocate an unused port for use as a server socket. The port number actually allocated may be retrieved from the created server socket using the fconfigure command to retrieve the -sockname option as described below.
proc Server {channel clientaddr clientport} {
puts "Connection from $clientaddr registered"
puts $channel [clock format [clock seconds]]
close $channel
}
socket -server Server 9900
vwait forever
And here is the corresponding client to talk to the server: set server localhost
set sockChan [socket $server 9900]
gets $sockChan line
close $sockChan
puts "The time on $server is $line"
source -rsrc resourceName ?fileName?
source -rsrcid resourceId ?fileName?
This command takes the contents of the specified file or resource and passes it to the Tcl interpreter as a text script. The return value from source is the return value of the last command executed in the script. If an error occurs in evaluating the contents of the script then the source command will return that error. If a return command is invoked from within the script then the remainder of the file will be skipped and the source command will return normally with the result from the return command.
The end-of-file character for files is ’\32’ (^Z) for all platforms. The source command will read files up to this character. This restriction does not exist for the read or gets commands, allowing for files containing code and data segments (scripted documents). If you require a ‘‘^Z’’ in code for string comparison, you can use ‘‘\032’’ or ‘‘\u001a’’, which will be safely substituted by the Tcl interpreter into ‘‘^Z’’.
The -rsrc and -rsrcid forms of this command are only available on Macintosh computers. These versions of the command allow you to source a script from a TEXT resource. You may specify what TEXT resource to source by either name or id. By default Tcl searches all open resource files, which include the current application and any loaded C extensions. Alternatively, you may specify the fileName where the TEXT resource can be found.
source foo.tcl
source bar.tcl
Alternatively: foreach scriptFile {foo.tcl bar.tcl} {
source $scriptFile
}
} text/html} \ -set mime_type text/html \ -set title en:source.n \ -set lang en ::xowiki::Page create ::xowiki::page87 -noinit \ -set description {} \ -set nls_language en_US \ -set text {\[\[en:#toc\]\]
\n\ \n
\ \n
\nReturns\ a\ list\ created\ by\nsplitting\ string\ at\ each\ character\ that\ is\ in\ the\ splitChars\ argument.\ Each\nelement\ of\ the\ result\ list\ will\ consist\ of\ the\ characters\ from\ string\ that\nlie\ between\ instances\ of\ the\ characters\ in\ splitChars.\ Empty\ list\ elements\nwill\ be\ generated\ if\ string\ contains\ adjacent\ characters\ in\ splitChars,\nor\ if\ the\ first\ or\ last\ character\ of\ string\ is\ in\ splitChars.\ If\ splitChars\nis\ an\ empty\ string\ then\ each\ character\ of\ string\ becomes\ a\ separate\ element\nof\ the\ result\ list.\ SplitChars\ defaults\ to\ the\ standard\ white-space\ characters.\n\n
split \;\"comp.lang.tcl.announce\" \;.
\n \; \; \; \; \;=>\; \;comp \;lang \;tcl \;announce
\n\n
See\ how\ the\ split\ command\ splits\ on\ every\ character\ in\ splitChars,\ which\ncan\ result\ in\ information\ loss\ if\ you\ are\ not\ careful:\ split \;\"alpha \;beta \;gamma\" \;\"temp\"
\n \; \; \; \; \;=>\; \;al \;\{ha \;b\} \;\{\} \;\{a \;ga\} \;\{\} \;a
\n\n
Extract\ the\ list\ words\ from\ a\ string\ that\ is\ not\ a\ well-formed\ list:\ split \;\"Example \;with \;\{unbalanced \;brace \;character\"
\n \; \; \; \; \;=>\; \;Example \;with \;\\\{unbalanced \;brace \;character
\n\n
Split\ a\ string\ into\ its\ constituent\ characters\ split \;\"Hello \;world\" \;\{\}
\n \; \; \; \; \;=>\; \;H \;e \;l \;l \;o \;\{ \;\} \;w \;o \;r \;l \;d
\n\n
Parsing\ Record-oriented\ Files\nParse\ a\ Unix\ /etc/passwd\ file,\ which\ consists\nof\ one\ entry\ per\ line,\ with\ each\ line\ consisting\ of\ a\ colon-separated\ list\nof\ fields:\ ## \;Read \;the \;file
\nset \;fid \;\[open \;/etc/passwd\]
\nset \;content \;\[read \;\$fid\]
\nclose \;\$fid
\n\n## \;Split \;into \;records \;on \;newlines
\nset \;records \;\[split \;\$content \;\"\\n\"\]
\n\n
## \;Iterate \;over \;the \;records
\nforeach \;rec \;\$records \;\{
\n\n
 \; \; \;## \;Split \;into \;fields \;on \;colons
\n \; \; \;set \;fields \;\[split \;\$rec \;\":\"\]
\n\n
 \; \; \;## \;Assign \;fields \;to \;variables \;and \;print \;some \;out...
\n \; \; \;lassign \;\$fields \;\\
\n \; \; \; \; \; \; \; \; \;userName \;password \;uid \;grp \;longName \;homeDir \;shell
\n \; \; \;puts \;\"\$longName \;uses \;\[file \;tail \;\$shell\] \;for \;a \;login \;shell\"
\n\}
\n\n
\ \n\ \n
\n\n
\n
\n\n text/html} \ -set mime_type text/html \ -set title en:split.n \ -set lang en ::xowiki::Page create ::xowiki::page88 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Performs one of several string operations, depending on option. The legal options (which may be abbreviated) are:
string first a 0a23456789abcdef 5
will return 10, but
string first a 0123456789abcdef 11
will return -1.
If charIndex is less than 0 or greater than or equal to the length of the string then an empty string is returned.
In the case of boolean, true and false, if the function will return 0, then the varname will always be set to 0, due to the varied nature of a valid boolean value.
string last a 0a23456789abcdef 15
will return 10, but
string last a 0a23456789abcdef 9
will return 1.
string map {abc 1 ab 2 a 3 1 0} 1abcaababcabababc
will return the string 01321221.
Note that if an earlier key is a prefix
of a later one, it will completely mask the later one. So if the previous
example is reordered like this,
string map {1 0 ab 2 a 3 abc 1} 1abcaababcabababc
it will return the string 02c322c222c.
set length [string length $string]
if {$length == 0} {
set isPrefix 0
} else {
set isPrefix [string equal -length $string $string "foobar"]
}
} text/html} \ -set mime_type text/html \ -set title en:string.n \ -set lang en ::xowiki::Page create ::xowiki::page89 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
string
This command performs variable substitutions, command substitutions, and backslash substitutions on its string argument and returns the fully-substituted result. The substitutions are performed in exactly the same way as for Tcl commands. As a result, the string argument is actually substituted twice, once by the Tcl parser in the usual fashion for Tcl commands, and again by the subst command.
If any of the -nobackslashes, -nocommands, or -novariables are specified, then the corresponding substitutions are not performed. For example, if -nocommands is specified, command substitution is not performed: open and close brackets are treated as ordinary characters with no special interpretation.
Note that the substitution of one kind can include substitution of other kinds. For example, even when the -novariables option is specified, command substitution is performed without restriction. This means that any variable substitution necessary to complete the command substitution will still take place. Likewise, any command substitution necessary to complete a variable substitution will take place, even when -nocommands is specified. See the EXAMPLES below.
If an error occurs during substitution, then subst will return that error. If a break exception occurs during command or variable substitution, the result of the whole substitution will be the string (as substituted) up to the start of the substitution that raised the exception. If a continue exception occurs during the evaluation of a command or variable substitution, an empty string will be substituted for that entire command or variable substitution (as long as it is well-formed Tcl.) If a return exception occurs, or any other return code is returned during command or variable substitution, then the returned value is substituted for that substitution. See the EXAMPLES below. In this way, all exceptional return codes are ‘‘caught’’ by subst. The subst command itself will either return an error, or will complete successfully.
When it performs
its substitutions, subst does not give any special treatment to double
quotes or curly braces (except within command substitutions) so the script
set a 44
returns ‘‘xyz {44}’’, not ‘‘xyz {$a}’’ and the script
subst {xyz {$a}}
set a "p\} q \{r"
return ‘‘xyz {p} q {r}’’, not ‘‘xyz {p\} q \{r}’’.
subst {xyz {$a}}
When command substitution is performed,
it includes any variable substitution necessary to evaluate the script.
set a 44
returns ‘‘$a 44’’, not ‘‘$a $a’’. Similarly, when variable substitution is performed,
it includes any command substitution necessary to retrieve the value of
the variable.
subst -novariables {$a [format $a]}
proc b {} {return c}
returns ‘‘[b] c’’, not ‘‘[b] tricky’’.
array set a {c c [b] tricky}
subst -nocommands {[b] $a([b])}
The continue and break exceptions allow command
substitutions to prevent substitution of the rest of the command substitution
and the rest of string respectively, giving script authors more options
when processing text using subst. For example, the script
subst {abc,[break],def}
returns ‘‘abc,’’, not ‘‘abc,,def’’ and the script
subst {abc,[continue;expr 1+2],def}
returns ‘‘abc,,def’’, not ‘‘abc,3,def’’.
Other exceptional return codes substitute
the returned value
subst {abc,[return foo;expr 1+2],def}
returns ‘‘abc,foo,def’’, not ‘‘abc,3,def’’ and
subst {abc,[return -code 10 foo;expr 1+2],def}
also returns ‘‘abc,foo,def’’, not ‘‘abc,3,def’’.
} text/html} \ -set mime_type text/html \ -set title en:subst.n \ -set lang en ::xowiki::Page create ::xowiki::page90 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
switch ?options? string {pattern body ?pattern body ...?}
The switch command matches its string argument against each of the pattern arguments in order. As soon as it finds a pattern that matches string it evaluates the following body argument by passing it recursively to the Tcl interpreter and returns the result of that evaluation. If the last pattern argument is default then it matches anything. If no pattern argument matches string and no default is given, then the switch command returns an empty string.
If the initial arguments to switch start with - then they are treated as options. The following options are currently supported:
Two syntaxes are provided for the pattern and body arguments. The first uses a separate argument for each of the patterns and commands; this form is convenient if substitutions are desired on some of the patterns or commands. The second form places all of the patterns and commands together into a single argument; the argument must have proper list structure, with the elements of the list being the patterns and commands. The second form makes it easy to construct multi-line switch commands, since the braces around the whole list make it unnecessary to include a backslash at the end of each line. Since the pattern arguments are in braces in the second form, no command or variable substitutions are performed on them; this makes the behavior of the second form different than the first form in some cases.
If a body is specified as ‘‘-’’ it means that the body for the next pattern should also be used as the body for this pattern (if the next pattern also has a body of ‘‘-’’ then the body after that is used, and so on). This feature makes it possible to share a single body among several patterns.
Beware of how you place comments in switch commands. Comments should only be placed inside the execution body of one of the patterns, and not intermingled with the patterns.
set foo "abc"
switch abc a - b {expr 1} $foo {expr 2} default {expr 3}
Using glob matching and the fall-through body is an alternative to writing
regular expressions with alternations, as can be seen here (this returns
1): switch -glob aaab {
a*b -
b {expr 1}
a* {expr 2}
default {expr 3}
}
Whenever nothing matches, the default clause (which must be last) is taken.
This example has a result of 3: switch xyz {
a -
b {
# Correct Comment Placement
expr 1
}
c {
expr 2
}
default {
expr 3
}
}
} text/html} \ -set mime_type text/html \ -set title en:switch.n \ -set lang en ::xowiki::Page create ::xowiki::page91 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The following rules define the syntax and semantics of the Tcl language:
There may be any number of variable substitutions in a single word. Variable substitution is not performed on words enclosed in braces.
Backslash substitution is not performed on words enclosed in braces, except for backslash-newline as described above.
Substitutions take place from left to
right, and each substitution is evaluated completely before attempting
to evaluate 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.
} text/html} \ -set mime_type text/html \ -set title en:Tcl.n \ -set lang en ::xowiki::Page create ::xowiki::page92 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_endOfWord.n \ -set lang en ::xowiki::Page create ::xowiki::page93 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_findLibrary.n \ -set lang en ::xowiki::Page create ::xowiki::page94 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_startOfNextWord.n \ -set lang en ::xowiki::Page create ::xowiki::page95 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_startOfPreviousWord.n \ -set lang en ::xowiki::Page create ::xowiki::page96 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_wordBreakAfter.n \ -set lang en ::xowiki::Page create ::xowiki::page97 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
auto_execok, auto_import, auto_load, auto_mkindex, auto_mkindex_old, auto_qualify, auto_reset, tcl_findLibrary, parray, tcl_endOfWord, tcl_startOfNextWord, tcl_startOfPreviousWord, tcl_wordBreakAfter, tcl_wordBreakBefore - standard library of Tcl proceduresSynopsis
auto_execok cmd auto_import pattern auto_load cmd auto_mkindex dir pattern pattern ... auto_mkindex_old dir pattern pattern ... auto_qualify command namespace auto_reset tcl_findLibrary basename version patch initScript enVarName varName parray arrayName tcl_endOfWord str start tcl_startOfNextWord str start tcl_startOfPreviousWord str start tcl_wordBreakAfter str start tcl_wordBreakBefore str start IntroductionTcl includes a library of Tcl procedures for commonly-needed functions. The procedures defined in the Tcl library are generic ones suitable for use by many different applications. The location of the Tcl library is returned by the info library command. In addition to the Tcl library, each application will normally have its own library of support procedures as well; the location of this library is normally given by the value of the $app_library global variable, where app is the name of the application. For example, the location of the Tk library is kept in the variable $tk_library. To access the procedures in the Tcl library, an application should source the file init.tcl in the library, for example with the Tcl command source [file join [info library] init.tcl] If the library procedure Tcl_Init is invoked from an application’s Tcl_AppInit procedure, this happens automatically. The code in init.tcl will define the unknown procedure and arrange for the other procedures to be loaded on-demand using the auto-load mechanism defined below. Command ProceduresThe following procedures are provided in the Tcl library: auto_execok cmd Determines whether there is an executable file or shell builtin by the name cmd. If so, it returns a list of arguments to be passed to exec to execute the executable file or shell builtin named by cmd. If not, it returns an empty string. This command examines the directories in the current search path (given by the PATH environment variable) in its search for an executable file named cmd. On Windows platforms, the search is expanded with the same directories and file extensions as used by exec. Auto_exec remembers information about previous searches in an array named auto_execs; this avoids the path search in future calls for the same cmd. The command auto_reset may be used to force auto_execok to forget its cached information. auto_import pattern Auto_import is invoked during namespace import to see if the imported commands specified by pattern reside in an autoloaded library. If so, the commands are loaded so that they will be available to the interpreter for creating the import links. If the commands do not reside in an autoloaded library, auto_import does nothing. The pattern matching is performed according to the matching rules of namespace import. auto_load cmd This command attempts to load the definition for a Tcl command named cmd. To do this, it searches an auto-load path, which is a list of one or more directories. The auto-load path is given by the global variable $auto_path if it exists. If there is no $auto_path variable, then the TCLLIBPATH environment variable is used, if it exists. Otherwise the auto-load path consists of just the Tcl library directory. Within each directory in the auto-load path there must be a file tclIndex that describes one or more commands defined in that directory and a script to evaluate to load each of the commands. The tclIndex file should be generated with the auto_mkindex command. If cmd is found in an index file, then the appropriate script is evaluated to create the command. The auto_load command returns 1 if cmd was successfully created. The command returns 0 if there was no index entry for cmd or if the script didn’t actually define cmd (e.g. because index information is out of date). If an error occurs while processing the script, then that error is returned. Auto_load only reads the index information once and saves it in the array auto_index; future calls to auto_load check for cmd in the array rather than re-reading the index files. The cached index information may be deleted with the command auto_reset. This will force the next auto_load command to reload the index database from disk. auto_mkindex dir pattern pattern ... Generates an index suitable for use by auto_load. The command searches dir for all files whose names match any of the pattern arguments (matching is done with the glob command), generates an index of all the Tcl command procedures defined in all the matching files, and stores the index information in a file named tclIndex in dir. If no pattern is given a pattern of *.tcl will be assumed. For example, the command auto_mkindex foo *.tcl will read all the .tcl files in subdirectory foo and generate a new index file foo/tclIndex. Auto_mkindex parses the Tcl scripts by sourcing them into a slave interpreter and monitoring the proc and namespace commands that are executed. Extensions can use the (undocumented) auto_mkindex_parser package to register other commands that can contribute to the auto_load index. You will have to read through auto.tcl to see how this works. Auto_mkindex_old parses the Tcl scripts in a relatively unsophisticated way: if any line contains the word proc as its first characters then it is assumed to be a procedure definition and the next word of the line is taken as the procedure’s name. Procedure definitions that don’t appear in this way (e.g. they have spaces before the proc) will not be indexed. If your script contains "dangerous" code, such as global initialization code or procedure names with special characters like $, *, [ or ], you are safer using auto_mkindex_old. auto_reset Destroys all the information cached by auto_execok and auto_load. This information will be re-read from disk the next time it is needed. Auto_reset also deletes any procedures listed in the auto-load index, so that fresh copies of them will be loaded the next time that they’re used. auto_qualify command namespace Computes a list of fully qualified names for command. This list mirrors the path a standard Tcl interpreter follows for command lookups: first it looks for the command in the current namespace, and then in the global namespace. Accordingly, if command is relative and namespace is not ::, the list returned has two elements: command scoped by namespace, as if it were a command in the namespace namespace; and command as if it were a command in the global namespace. Otherwise, if either command is absolute (it begins with ::), or namespace is ::, the list contains only command as if it were a command in the global namespace. Auto_qualify is used by the auto-loading facilities in Tcl, both for producing auto-loading indexes such as pkgIndex.tcl, and for performing the actual auto-loading of functions at runtime. tcl_findLibrary basename version patch initScript enVarName varName This is a standard search procedure for use by extensions during their initialization. They call this procedure to look for their script library in several standard directories. The last component of the name of the library directory is normally basenameversion (e.g., tk8.0), but it might be "library" when in the build hierarchies. The initScript file will be sourced into the interpreter once it is found. The directory in which this file is found is stored into the global variable varName. If this variable is already defined (e.g., by C code during application initialization) then no searching is done. Otherwise the search looks in these directories: the directory named by the environment variable enVarName; relative to the Tcl library directory; relative to the executable file in the standard installation bin or bin/arch directory; relative to the executable file in the current build tree; relative to the executable file in a parallel build tree. parray arrayName Prints on standard output the names and values of all the elements in the array arrayName. ArrayName must be an array accessible to the caller of parray. It may be either local or global. tcl_endOfWord str start Returns the index of the first end-of-word location that occurs after a starting index start in the string str. An end-of-word location is defined to be the first non-word character following the first word character after the starting point. Returns -1 if there are no more end-of-word locations after the starting point. See the description of tcl_wordchars and tcl_nonwordchars below for more details on how Tcl determines which characters are word characters. tcl_startOfNextWord str start Returns the index of the first start-of-word location that occurs after a starting index start in the string str. A start-of-word location is defined to be the first word character following a non-word character. Returns -1 if there are no more start-of-word locations after the starting point. tcl_startOfPreviousWord str start Returns the index of the first start-of-word location that occurs before a starting index start in the string str. Returns -1 if there are no more start-of-word locations before the starting point. tcl_wordBreakAfter str start Returns the index of the first word boundary after the starting index start in the string str. Returns -1 if there are no more boundaries after the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. tcl_wordBreakBefore str start Returns the index of the first word boundary before the starting index start in the string str. Returns -1 if there are no more boundaries before the starting point in the given string. The index returned refers to the second character of the pair that comprises a boundary. VariablesThe following global variables are defined or used by the procedures in the Tcl library: auto_execs Used by auto_execok to record information about whether particular commands exist as executable files. auto_index Used by auto_load to save the index information read from disk. auto_noexec If set to any value, then unknown will not attempt to auto-exec any commands. auto_noload If set to any value, then unknown will not attempt to auto-load any commands. auto_path If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. This variable is initialized during startup to contain, in order: the directories listed in the TCLLIBPATH environment variable, the directory named by the $tcl_library variable, the parent directory of $tcl_library, the directories listed in the $tcl_pkgPath variable. env(TCL_LIBRARY) If set, then it specifies the location of the directory containing library scripts (the value of this variable will be assigned to the tcl_library variable and therefore returned by the command info library). If this variable isn’t set then a default value is used. env(TCLLIBPATH) If set, then it must contain a valid Tcl list giving directories to search during auto-load operations. Directories must be specified in Tcl format, using "/" as the path separator, regardless of platform. This variable is only used when initializing the auto_path variable. tcl_nonwordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a non-word character. On Windows platforms, spaces, tabs, and newlines are considered non-word characters. Under Unix, everything but numbers, letters and underscores are considered non-word characters. tcl_wordchars This variable contains a regular expression that is used by routines like tcl_endOfWord to identify whether a character is part of a word or not. If the pattern matches a character, the character is considered to be a word character. On Windows platforms, words are comprised of any character that is not a space, tab, or newline. Under Unix, words are comprised of numbers, letters or underscores. unknown_pending Used by unknown to record the command(s) for which it is searching. It is used to detect errors where unknown recurses on itself infinitely. The variable is unset before unknown returns. See Alsoinfo(n), re_syntax(n) Keywordsauto-exec, auto-load, library, unknown, word, whitespace } text/html} \ -set mime_type text/html \ -set title en:tcl_wordBreakBefore.n \ -set lang en ::xowiki::Page create ::xowiki::page98 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Name
tcltest - Test harness support code and utilitiesSynopsis
package require tcltest ?2.2.5? tcltest::test name description ?option value ...? tcltest::test name description ?constraints? body result tcltest::loadTestedCommands tcltest::makeDirectory name ?directory? tcltest::removeDirectory name ?directory? tcltest::makeFile contents name ?directory? tcltest::removeFile name ?directory? tcltest::viewFile name ?directory? tcltest::cleanupTests ?runningMultipleTests? tcltest::runAllTests tcltest::configure tcltest::configure option tcltest::configure option value ?option value ...? tcltest::customMatch mode command tcltest::testConstraint constraint ?value? tcltest::outputChannel ?channelID? tcltest::errorChannel ?channelID? tcltest::interpreter ?interp? tcltest::debug ?level? tcltest::errorFile ?filename? tcltest::limitConstraints ?boolean? tcltest::loadFile ?filename? tcltest::loadScript ?script? tcltest::match ?patternList? tcltest::matchDirectories ?patternList? tcltest::matchFiles ?patternList? tcltest::outputFile ?filename? tcltest::preserveCore ?level? tcltest::singleProcess ?boolean? tcltest::skip ?patternList? tcltest::skipDirectories ?patternList? tcltest::skipFiles ?patternList? tcltest::temporaryDirectory ?directory? tcltest::testsDirectory ?directory? tcltest::verbose ?level? tcltest::test name description optionList tcltest::bytestring string tcltest::normalizeMsg msg tcltest::normalizePath pathVar tcltest::workingDirectory ?dir?Description
The tcltest package provides several utility commands useful in the construction of test suites for code instrumented to be run by evaluation of Tcl commands. Notably the built-in commands of the Tcl library itself are tested by a test suite using the tcltest package.
All the commands provided by the tcltest package are defined in and exported from the ::tcltest namespace, as indicated in the SYNOPSIS above. In the following sections, all commands will be described by their simple names, in the interest of brevity.
The central command of tcltest is [test] that defines and runs a test. Testing with [test] involves evaluation of a Tcl script and comparing the result to an expected result, as configured and controlled by a number of options. Several other commands provided by tcltest govern the configuration of [test] and the collection of many [test] commands into test suites.
See CREATING TEST SUITES WITH TCLTEST below for an extended example of how to use the commands of tcltest to produce test suites for your Tcl-enabled code.
Commands
Prints statistics about the tests run and removes files that were created by [makeDirectory] and [makeFile] since the last [cleanupTests]. Names of files and directories in the directory [configure -tmpdir] created since the last [cleanupTests], but not created by [makeFile] or [makeDirectory] are printed to [outputChannel]. This command also restores the original shell environment, as described by the ::env array. Returns an empty string.
If the environment variable ::env(TCLTEST_OPTIONS) exists when the tcltest package is loaded (by [package require tcltest]) then its value is taken as a list of arguments to pass to [configure]. This allows the default values of the configuration options to be set by the environment.
The remaining commands provided by tcltest have better alternatives provided by tcltest or Tcl itself. They are retained to support existing test suites, but should be avoided in new code.
The [test] command is the heart of the tcltest package. Its essential function is to evaluate a Tcl script and compare the result with an expected result. The options of [test] define the test script, the environment in which to evaluate it, the expected result, and how the compare the actual result to the expected result. Some configuration options of tcltest also influence how [test] operates.
The
valid options for [test] are summarized:
test name description
The name may be any string. It is conventional to choose a name according
to the pattern:
?-constraints keywordList|expression?
?-setup setupScript?
?-body testScript?
?-cleanup cleanupScript?
?-result expectedAnswer?
?-output expectedOutput?
?-errorOutput expectedError?
?-returnCodes codeList?
?-match mode?
target-majorNum.minorNum
For white-box (regression) tests, the target should be the name of the C
function or Tcl procedure being tested. For black-box tests, the target
should be the name of the feature being tested. Some conventions call for
the names of black-box tests to have the suffix _bb. Related tests should
share a major number. As a test suite evolves, it is best to have the same
test name continue to correspond to the same test, so that it remains meaningful
to say things like ‘‘Test foo-1.3 passed in all releases up to 3.4, but began
failing in release 3.5.’’
During evaluation of [test], the name will be compared to the lists of string matching patterns returned by [configure -match], and [configure -skip]. The test will be run only if name matches any of the patterns from [configure -match] and matches none of the patterns from [configure -skip].
The description should be a short textual description of the test. The description is included in output produced by the test, typically test failure messages. Good description values should briefly explain the purpose of the test to users of a test suite. The name of a Tcl or C function being tested should be included in the description for regression tests. If the test case exists to reproduce a bug, include the bug ID in the description.
Valid attributes and associated values are:
To pass, a test must successfully evaluate its -setup, -body, and -cleanup scripts. The return code of the -body script and its result must match expected values, and if specified, output and error data from the test must match expected -output and -errorOutput values. If any of these conditions are not met, then the test fails. Note that all scripts are evaluated in the context of the caller of [test].
As long as [test] is called with valid syntax and legal values for all attributes, it will not raise an error. Test failures are instead reported as output written to [outputChannel]. In default operation, a successful test produces no output. The output messages produced by [test] are controlled by the [configure -verbose] option as described in CONFIGURABLE OPTIONS below. Any output produced by the test scripts themselves should be produced using [::puts] to [outputChannel] or [errorChannel], so that users of the test suite may easily capture output with the [configure -outfile] and [configure -errfile] options, and so that the -output and -errorOutput attributes work properly.
Constraints are used to determine whether or not a test should be skipped. Each constraint has a name, which may be any string, and a boolean value. Each [test] has a -constraints value which is a list of constraint names. There are two modes of constraint control. Most frequently, the default mode is used, indicated by a setting of [configure -limitconstraints] to false. The test will run only if all constraints in the list are true-valued. Thus, the -constraints option of [test] is a convenient, symbolic way to define any conditions required for the test to be possible or meaningful. For example, a [test] with -constraints unix will only be run if the constraint unix is true, which indicates the test suite is being run on a Unix platform.
Each [test] should include whatever -constraints are required to constrain it to run only where appropriate. Several constraints are pre-defined in the tcltest package, listed below. The registration of user-defined constraints is performed by the [testConstraint] command. User-defined constraints may appear within a test file, or within the script specified by the [configure -load] or [configure -loadfile] options.
The following is a list of constraints pre-defined by the tcltest package itself:
The alternative
mode of constraint control is enabled by setting [configure -limitconstraints]
to true. With that configuration setting, all existing constraints other
than those in the constraint list returned by [configure -constraints] are
set to false. When the value of [configure -constraints] is set, all those
constraints are set to true. The effect is that when both options [configure
-constraints] and [configure -limitconstraints] are in use, only those tests
including only constraints from the [configure -constraints] list are run;
all others are skipped. For example, one might set up a configuration with
configure -constraints knownBug \
to run exactly those tests that exercise known bugs, and discover whether
any of them pass, indicating the bug had been fixed.
-limitconstraints true \
-verbose pass
The single command [runAllTests] is evaluated to run an entire test suite, spanning many files and directories. The configuration options of tcltest control the precise operations. The [runAllTests] command begins by printing a summary of its configuration to [outputChannel].
Test files to be evaluated are sought in the directory [configure -testdir]. The list of files in that directory that match any of the patterns in [configure -file] and match none of the patterns in [configure -notfile] is generated and sorted. Then each file will be evaluated in turn. If [configure -singleproc] is true, then each file will be [source]d in the caller’s context. If it is false, then a copy of [interpreter] will be [exec]d to evaluate each file. The multi-process operation is useful when testing can cause errors so severe that a process terminates. Although such an error may terminate a child process evaluating one file, the master process can continue with the rest of the test suite. In multi-process operation, the configuration of tcltest in the master process is passed to the child processes as command line arguments, with the exception of [configure -outfile]. The [runAllTests] command in the master process collects all output from the child processes and collates their results into one master report. Any reports of individual test failures, or messages requested by a [configure -verbose] setting are passed directly on to [outputChannel] by the master process.
After evaluating all selected test files, a summary of the results is printed to [outputChannel]. The summary includes the total number of [test]s evaluated, broken down into those skipped, those passed, and those failed. The summary also notes the number of files evaluated, and the names of any files with failing tests or errors. A list of the constraints that caused tests to be skipped, and the number of tests skipped for each is also printed. Also, messages are printed if it appears that evaluation of a test file has caused any temporary files to be left behind in [configure -tmpdir].
Having completed and summarized all selected test files, [runAllTests] then recursively acts on subdirectories of [configure -testdir]. All subdirectories that match any of the patterns in [configure -relateddir] and do not match any of the patterns in [configure -asidefromdir] are examined. If a file named all.tcl is found in such a directory, it will be [source]d in the caller’s context. Whether or not an examined directory contains an all.tcl file, its subdirectories are also scanned against the [configure -relateddir] and [configure -asidefromdir] patterns. In this way, many directories in a directory tree can have all their test files evaluated by a single [runAllTests] command.
The fundamental element of a test suite is the individual [test] command. We begin with several examples.
test example-1.0 {normal return} {
format %s value
} value
test example-1.1 {test file existence} -setup {
set file [makeFile {} test]
} -body {
file exists $file
} -cleanup {
removeFile test
} -result 1
test example-1.2 {error return} -body {
error message
} -returnCodes error -result message
test example-1.3 {user owns created files} -constraints {
unix
} -setup {
set file [makeFile {} test]
} -body {
file attributes $file -owner
} -cleanup {
removeFile test
} -result $::tcl_platform(user)
At the next higher layer of organization, several [test] commands are gathered together into a single test file. Test files should have names with the .test extension, because that is the default pattern used by [runAllTests] to find test files. It is a good rule of thumb to have one test file for each source code file of your project. It is good practice to edit the test file and the source code file together, keeping tests synchronized with code changes.
Most of the code in the test file should be the [test] commands. Use constraints to skip tests, rather than conditional evaluation of [test]. That is, do this:
testConstraint X [expr $myRequirement]
test goodConditionalTest {} X {
# body
} result
and do not do this: if $myRequirement {
test badConditionalTest {} {
#body
} result
}
Use the -setup and -cleanup options to establish and release all context requirements of the test body. Do not make tests depend on prior tests in the file. Those prior tests might be skipped. If several consecutive tests require the same context, the appropriate setup and cleanup scripts may be stored in variable for passing to each tests -setup and -cleanup options. This is a better solution than performing setup outside of [test] commands, because the setup will only be done if necessary, and any errors during setup will be reported, and not cause the test file to abort.
A test file should be able to be combined with other test files and not interfere with them, even when [configure -singleproc 1] causes all files to be evaluated in a common interpreter. A simple way to achieve this is to have your tests define all their commands and variables in a namespace that is deleted when the test file evaluation is complete. A good namespace to use is a child namespace test of the namespace of the module you are testing.
A test file should also be able to be evaluated directly as a script, not depending on being called by a master [runAllTests]. This means that each test file should process command line arguments to give the tester all the configuration control that tcltest provides.
After all [test]s in a test file, the command [cleanupTests] should be called.
package require tcltest 2.2
eval ::tcltest::configure $argv
package require example
namespace eval ::example::test {
namespace import ::tcltest::*
testConstraint X [expr {...}]
variable SETUP {#common setup code}
variable CLEANUP {#common cleanup code}
test example-1 {} -setup $SETUP -body {
# First test
} -cleanup $CLEANUP -result {...}
test example-2 {} -constraints X -setup $SETUP -body {
# Second test; constrained
} -cleanup $CLEANUP -result {...}
test example-3 {} {
# Third test; no context required
} {...}
cleanupTests
}
namespace delete ::example::test
The next level of organization is a full test suite, made up of several test files. One script is used to control the entire suite. The basic function of this script is to call [runAllTests] after doing any necessary setup. This script is usually named all.tcl because that’s the default name used by [runAllTests] when combining multiple test suites into one testing run.
package require Tcl 8.4
package require tcltest 2.2
package require example
::tcltest::configure -testdir
[file dirname [file normalize [info script]]]
eval ::tcltest::configure $argv
::tcltest::runAllTests
A number of commands and variables in the ::tcltest namespace
provided by earlier releases of tcltest have not been documented here.
They are no longer part of the supported public interface of tcltest and
should not be used in new test suites. However, to continue to support
existing test suites written to the older interface specifications, many
of those deprecated commands and variables still work as before. For example,
in many circumstances, [configure] will be automatically called shortly
after [package require tcltest 2.1] succeeds with arguments from the variable
::argv. This is to support test suites that depend on the old behavior
that tcltest was automatically configured from command line arguments.
New test files should not depend on this, but should explicitly include
eval ::tcltest::configure $::argv
to establish a configuration from command line arguments.
test level-1.1 {level 1} {
-body {
test level-2.1 {level 2} {
}
}
}
any script executed in level-2.1 may be executed at the same stack level
as the script defined for level-1.1. In addition, while two [test]s have been run, results will only be reported by [cleanupTests] for tests at the same level as test level-1.1. However, test results for all tests run prior to level-1.1 will be available when test level-2.1 runs. What this means is that if you try to access the test results for test level-2.1, it will may say that ’m’ tests have run, ’n’ tests have been skipped, ’o’ tests have passed and ’p’ tests have failed, where ’m’, ’n’, ’o’, and ’p’ refer to tests that were run at the same test level as test level-1.1.
Implementation of output and error comparison in the test command depends on usage of ::puts in your application code. Output is intercepted by redefining the ::puts command while the defined test script is being run. Errors thrown by C procedures or printed directly from C applications will not be caught by the test command. Therefore, usage of the -output and -errorOuput options to [test] is useful only for pure Tcl applications that use [::puts] to produce output.
The following global variables are created and managed automatically by the Tcl library. Except where noted below, these variables should normally be treated as read-only by application-specific code and by users.
Under Windows, the environment variables PATH and COMSPEC in any capitalization are converted automatically to upper case. For instance, the PATH variable could be exported by the operating system as ‘‘path’’, ‘‘Path’’, ‘‘PaTh’’, etc., causing otherwise simple Tcl code to have to support many special cases. All other environment variables inherited by Tcl are left unmodified. Setting an env array variable to blank is the same as unsetting it as this is the behavior of the underlying Windows OS. It should be noted that relying on an existing and empty environment variable won’t work on windows and is discouraged for cross-platform usage.
On the Macintosh, the environment variable is constructed by Tcl as no global environment variable exists. The environment variables that are created for Tcl include:
- LOGIN
- This holds the Chooser name of the Macintosh.
- USER
- This also holds the Chooser name of the Macintosh.
- SYS_FOLDER
- The path to the system directory.
- APPLE_M_FOLDER
- The path to the Apple Menu directory.
- CP_FOLDER
- The path to the control panels directory.
- DESK_FOLDER
- The path to the desk top directory.
- EXT_FOLDER
- The path to the system extensions directory.
- PREF_FOLDER
- The path to the preferences directory.
- PRINT_MON_FOLDER
- The path to the print monitor directory.
- SHARED_TRASH_FOLDER
- The path to the network trash directory.
- TRASH_FOLDER
- The path to the trash directory.
- START_UP_FOLDER
- The path to the start up directory.
- HOME
- The path to the application’s default directory.
You can also create your own environment variables for the Macintosh. A file named Tcl Environment Variables may be placed in the preferences folder in the Mac system folder. Each line of this file should be of the form VAR_NAME=var_data.
The last alternative is to place environment variables in a ’STR#’ resource named Tcl Environment Variables of the application. This is considered a little more ‘‘Mac like’’ than a Unix style Environment Variable file. Each entry in the ’STR#’ resource has the same format as above. The source code file tclMacEnv.c contains the implementation of the env mechanisms. This file contains many #define’s that allow customization of the env mechanisms to fit your applications needs.
To set errorCode, applications should use library procedures such as Tcl_SetErrorCode and Tcl_PosixError, or they may invoke the error command. If one of these methods hasn’t been used, then the Tcl interpreter will reset the variable to NONE after the next error.
All interpreters in a process share a single tcl_precision value: changing it in one interpreter will affect all other interpreters as well. However, safe interpreters are not allowed to modify the variable.
This variable and functionality only exist if TCL_COMPILE_DEBUG was defined during Tcl’s compilation.
This variable and functionality only exist if TCL_COMPILE_DEBUG was defined during Tcl’s compilation.
The wish executably additionally specifies the following global variable:
} text/html} \ -set mime_type text/html \ -set title en:tclvars.n \ -set lang en ::xowiki::Page create ::xowiki::page100 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
Returns an integer string giving the current access position in channelId. This value returned is a byte offset that can be passed to seek in order to set the channel to a particular position. Note that this value is in terms of bytes, not characters like read. The value returned is -1 for channels that do not support seeking.
ChannelId must be an identifier for an open channel such as a Tcl standard channel (stdin, stdout, or stderr), the return value from an invocation of open or socket, or the result of a channel creation command provided by a Tcl extension.
# Save the offset in case we need to undo the read...
set offset [tell $chan]
if {[read $chan 6] eq "foobar"} {
gets $chan line
} else {
set line {}
# Undo the read...
seek $chan $offset
}
} text/html} \ -set mime_type text/html \ -set title en:tell.n \ -set lang en ::xowiki::Page create ::xowiki::page101 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command will call the Tcl interpreter count
times to evaluate script (or once if count isn’t specified). It will then
return a string of the form
503 microseconds per iteration
which indicates the average amount of time required per iteration, in microseconds.
Time is measured in elapsed time, not CPU time.
time {
for {set i 0} {$i<1000} {incr i} {
# empty body
}
}
} text/html} \ -set mime_type text/html \ -set title en:time.n \ -set lang en ::xowiki::Page create ::xowiki::page102 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command causes Tcl commands to be executed whenever certain operations are invoked. The legal option’s (which may be abbreviated) are:
Ops indicates which operations are of interest, and is a list of one or more of the following items:
When the trace triggers, depending on the operations being
traced, a number of arguments are appended to command so that the actual
command is as follows:
command oldName newName op
OldName and newName give the traced command’s current (old) name, and the
name to which it is being renamed (the empty string if this is a ’delete’
operation). Op indicates what operation is being performed on the command,
and is one of rename or delete as defined above. The trace operation cannot
be used to stop a command from being deleted. Tcl will always remove the
command once the trace is complete. Recursive renaming or deleting will
not cause further traces of the same type to be evaluated, so a delete
trace which itself deletes the command, or a rename trace which itself
renames the command will not cause further trace evaluations to occur. Both
oldName and newName are fully qualified with any namespace(s) in which
they appear.
Ops indicates which operations are of interest, and is a list of one or more of the following items:
When the trace triggers, depending on the operations being traced, a number of arguments are appended to command so that the actual command is as follows:
For enter and enterstep operations:
command command-string op
Command-string gives the complete current command being executed (the traced
command for a enter operation, an arbitrary command for a enterstep operation),
including all arguments in their fully expanded form. Op indicates what
operation is being performed on the command execution, and is one of enter
or enterstep as defined above. The trace operation can be used to stop
the command from executing, by deleting the command in question. Of course
when the command is subsequently executed, an ’invalid command’ error will
occur.
For leave and leavestep operations:
command command-string code result op
Command-string gives the complete current command being executed (the traced
command for a enter operation, an arbitrary command for a enterstep operation),
including all arguments in their fully expanded form. Code gives the result
code of that execution, and result the result string. Op indicates what
operation is being performed on the command execution, and is one of leave
or leavestep as defined above. Note that the creation of many enterstep
or leavestep traces can lead to unintuitive results, since the invoked
commands from one trace can themselves lead to further command invocations
for other traces.
Command executes in the same context as the code that invoked the traced operation: thus the command, if invoked from a procedure, will have access to the same local variables as code in the procedure. This context may be different than the context in which the trace was created. If command invokes a procedure (which it normally does) then the procedure will have to use upvar or uplevel commands if it wishes to access the local variables of the code which invoked the trace operation.
While command is executing during an execution trace, traces on name are temporarily disabled. This allows the command to execute name in its body without invoking any other traces again. If an error occurs while executing the command body, then the command name as a whole will return that same error.
When multiple traces are set on name, then for enter and enterstep operations, the traced commands are invoked in the reverse order of how the traces were originally created; and for leave and leavestep operations, the traced commands are invoked in the original order of creation.
The behavior of execution traces is currently undefined for a command name imported into another namespace.
Ops indicates which operations are of interest, and is a list of one or more of the following items:
When the trace triggers, three arguments are appended to command
so that the actual command is as follows:
command name1 name2 op
Name1 and name2 give the name(s) for the variable being accessed: if the
variable is a scalar then name1 gives the variable’s name and name2 is an
empty string; if the variable is an array element then name1 gives the
name of the array and name2 gives the index into the array; if an entire
array is being deleted and the trace was registered on the overall array,
rather than a single element, then name1 gives the array name and name2
is an empty string. Name1 and name2 are not necessarily the same as the
name used in the trace variable command: the upvar command allows a procedure
to reference a variable under a different name. Op indicates what operation
is being performed on the variable, and is one of read, write, or unset
as defined above.
Command executes in the same context as the code that invoked the traced operation: if the variable was accessed as part of a Tcl procedure, then command will have access to the same local variables as code in the procedure. This context may be different than the context in which the trace was created. If command invokes a procedure (which it normally does) then the procedure will have to use upvar or uplevel if it wishes to access the traced variable. Note also that name1 may not necessarily be the same as the name used to set the trace on the variable; differences can occur if the access is made through a variable defined with the upvar command.
For read and write traces, command can modify the variable to affect the result of the traced operation. If command modifies the value of a variable during a read or write trace, then the new value will be returned as the result of the traced operation. The return value from command is ignored except that if it returns an error of any sort then the traced operation also returns an error with the same error message returned by the trace command (this mechanism can be used to implement read-only variables, for example). For write traces, command is invoked after the variable’s value has been changed; it can write a new value into the variable to override the original value specified in the write operation. To implement read-only variables, command will have to restore the old value of the variable.
While command is executing during a read or write trace, traces on the variable are temporarily disabled. This means that reads and writes invoked by command will occur directly, without invoking command (or any other traces) again. However, if command unsets the variable then unset traces will be invoked.
When an unset trace is invoked, the variable has already been deleted: it will appear to be undefined with no traces. If an unset occurs because of a procedure return, then the trace will be invoked in the variable context of the procedure being returned to: the stack frame of the returning procedure will no longer exist. Traces are not disabled during unset traces, so if an unset trace command creates a new trace and accesses the variable, the trace will be invoked. Any errors in unset traces are ignored.
If there are multiple traces on a variable they are invoked in order of creation, most-recent first. If one trace returns an error, then no further traces are invoked for the variable. If an array element has a trace set, and there is also a trace set on the array as a whole, the trace on the overall array is invoked before the one on the element.
Once created, the trace remains in effect either until the trace is removed with the trace remove variable command described below, until the variable is unset, or until the interpreter is deleted. Unsetting an element of array will remove any traces on that element, but will not remove traces on the overall array.
This command returns an empty string.
For backwards compatibility, three other subcommands are available:
This is equivalent to trace info variable name
- trace variable name ops command
- This is equivalent to trace add variable name ops command.
- trace vdelete name ops command
- This is equivalent to trace remove variable name ops command
- trace vinfo name
These subcommands are deprecated and will likely be removed in a future version of Tcl. They use an older syntax in which array, read, write, unset are replaced by a, r, w and u respectively, and the ops argument is not a list, but simply a string concatenation of the operations, such as rwua.
proc tracer {varname args} {
upvar #0 $varname var
puts "$varname was updated to be \"$var\""
}
trace add variable foo write "tracer foo"
trace add variable bar write "tracer bar"
Ensure that the global variable foobar always contains the product of the
global variables foo and bar: proc doMult args {
global foo bar foobar
set foobar [expr {$foo * $bar}]
}
trace add variable foo write doMult
trace add variable bar write doMult
} text/html} \ -set mime_type text/html \ -set title en:trace.n \ -set lang en ::xowiki::Page create ::xowiki::page103 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command is invoked by the Tcl interpreter whenever a script tries to invoke a command that doesn’t exist. The default implementation of unknown is a library procedure defined when Tcl initializes an interpreter. You can override the default unknown to change its functionality. Note that there is no default implementation of unknown in a safe interpreter.
If the Tcl interpreter encounters a command name for which there is not a defined command, then Tcl checks for the existence of a command named unknown. If there is no such command, then the interpreter returns an error. If the unknown command exists, then it is invoked with arguments consisting of the fully-substituted name and arguments for the original non-existent command. The unknown command typically does things like searching through library directories for a command procedure with the name cmdName, or expanding abbreviated command names to full-length, or automatically executing unknown commands as sub-processes. In some cases (such as expanding abbreviations) unknown will change the original command slightly and then (re-)execute it. The result of the unknown command is used as the result for the original non-existent command.
The default implementation of unknown behaves as follows. It first calls the auto_load library procedure to load the command. If this succeeds, then it executes the original command with its original arguments. If the auto-load fails then unknown calls auto_execok to see if there is an executable file by the name cmd. If so, it invokes the Tcl exec command with cmd and all the args as arguments. If cmd can’t be auto-executed, unknown checks to see if the command was invoked at top-level and outside of any script. If so, then unknown takes two additional steps. First, it sees if cmd has one of the following three forms: !!, !event, or ^old^new?^?. If so, then unknown carries out history substitution in the same way that csh would for these constructs. Finally, unknown checks to see if cmd is a unique abbreviation for an existing Tcl command. If so, it expands the command name and executes the command with the original arguments. If none of the above efforts has been able to execute the command, unknown generates an error return. If the global variable auto_noload is defined, then the auto-load step is skipped. If the global variable auto_noexec is defined then the auto-exec step is skipped. Under normal circumstances the return value from unknown is the return value from the command that was eventually executed.
# Provide our own implementation
# Save the original one so we can chain to it
rename unknown _original_unknown
proc unknown args {
puts stderr "WARNING: unknown command: $args"
uplevel 1 [list _original_unknown {expand}$args]
}
} text/html} \ -set mime_type text/html \ -set title en:unknown.n \ -set lang en ::xowiki::Page create ::xowiki::page104 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command removes one or more variables. Each name is a variable name, specified in any of the ways acceptable to the set command. If a name refers to an element of an array then that element is removed without affecting the rest of the array. If a name consists of an array name with no parenthesized index, then the entire array is deleted. The unset command returns an empty string as result. If -nocomplain is specified as the first argument, any possible errors are suppressed. The option may not be abbreviated, in order to disambiguate it from possible variable names. The option -- indicates the end of the options, and should be used if you wish to remove a variable with the same name as any of the options. If an error occurs, any variables after the named one causing the error not deleted. An error can occur when the named variable doesn’t exist, or the name refers to an array element but the variable is a scalar, or the name refers to a variable in a non-existent namespace.
array set squares {
1 1 6 36
2 4 7 49
3 9 8 64
4 16 9 81
5 25 10 100
}
puts "The squares are:"
parray squares
unset squares(1)
squares(4)
squares(6)
unset squares(8)
squares(9)
squares(10)
puts "The prime squares are:"
parray squares
} text/html} \ -set mime_type text/html \ -set title en:unset.n \ -set lang en ::xowiki::Page create ::xowiki::page105 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command is used to bring the application ‘‘up to date’’ by entering the event loop repeatedly until all pending events (including idle callbacks) have been processed.
If the idletasks keyword is specified as an argument to the command, then no new events or errors are processed; only idle callbacks are invoked. This causes operations that are normally deferred, such as display updates and window layout calculations, to be performed immediately.
The update idletasks command is useful in scripts where changes have been made to the application’s state and you want those changes to appear on the display immediately, rather than waiting for the script to complete. Most display updates are performed as idle callbacks, so update idletasks will cause them to run. However, there are some kinds of updates that only happen in response to events, such as those triggered by window size changes; these updates will not occur in update idletasks.
The update command with no options is useful in scripts where you are performing a long-running computation but you still want the application to respond to events such as user interactions; if you occasionally call update then user input will be processed during the next call to update.
set x 1000
set done 0
after 1000 set done 1
while {!$done} {
# A very silly example!
set x [expr {log($x) ** 2.8}]
# Test to see if our time-limit has been hit. This would
# also give a chance for serving network sockets and, if
# the Tk package is loaded, updating a user interface.
update
}
} text/html} \ -set mime_type text/html \ -set title en:update.n \ -set lang en ::xowiki::Page create ::xowiki::page106 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
All of the arg arguments are concatenated as if they had been passed to concat; the result is then evaluated in the variable context indicated by level. Uplevel returns the result of that evaluation.
If level is an integer then it gives a distance (up the procedure calling stack) to move before executing the command. If level consists of # followed by a number then the number gives an absolute level number. If level is omitted then it defaults to 1. Level cannot be defaulted if the first command argument starts with a digit or #.
For example, suppose that procedure a was invoked from top-level, and that it called b, and that b called c. Suppose that c invokes the uplevel command. If level is 1 or #2 or omitted, then the command will be executed in the variable context of b. If level is 2 or #1 then the command will be executed in the variable context of a. If level is 3 or #0 then the command will be executed at top-level (only global variables will be visible).
The uplevel
command causes the invoking procedure to disappear from the procedure calling
stack while the command is being executed. In the above example, suppose
c invokes the command
uplevel 1 {set x 43; d}
where d is another Tcl procedure. The set command will modify the variable
x in b’s context, and d will execute at level 3, as if called from b. If
it in turn executes the command
uplevel {set x 42}
then the set command will modify the same variable x in b’s context: the
procedure c does not appear to be on the call stack when d is executing.
The command ‘‘info level’’ may be used to obtain the level of the current
procedure.
Uplevel makes it possible to implement new control constructs as Tcl procedures (for example, uplevel could be used to implement the while construct as a Tcl procedure).
namespace eval is another way (besides procedure calls) that the Tcl naming context can change. It adds a call frame to the stack to represent the namespace context. This means each namespace eval command counts as another call level for uplevel and upvar commands. For example, info level 1 will return a list describing a command that is either the outermost procedure call or the outermost namespace eval command. Also, uplevel #0 evaluates a script at top-level in the outermost namespace (the global namespace).
proc do {body while condition} {
if {$while ne "while"} {
error "required word missing"
}
set conditionCmd [list expr $condition]
while {1} {
uplevel 1 $body
if {![uplevel 1 $conditionCmd]} {
break
}
}
}
} text/html} \ -set mime_type text/html \ -set title en:uplevel.n \ -set lang en ::xowiki::Page create ::xowiki::page107 -noinit \ -set description {} \ -set nls_language en_US \ -set text {\[\[en:#toc\]\]
\n\ \n
\ \n
\nThis\ncommand\ arranges\ for\ one\ or\ more\ local\ variables\ in\ the\ current\ procedure\nto\ refer\ to\ variables\ in\ an\ enclosing\ procedure\ call\ or\ to\ global\ variables.\nLevel\ may\ have\ any\ of\ the\ forms\ permitted\ for\ the\ uplevel\ command,\ and\nmay\ be\ omitted\ if\ the\ first\ letter\ of\ the\ first\ otherVar\ isn&rsquo\;t\ #\ or\ a\ digit\n(it\ defaults\ to\ 1).\ For\ each\ otherVar\ argument,\ upvar\ makes\ the\ variable\nby\ that\ name\ in\ the\ procedure\ frame\ given\ by\ level\ (or\ at\ global\ level,\nif\ level\ is\ #0)\ accessible\ in\ the\ current\ procedure\ by\ the\ name\ given\ in\nthe\ corresponding\ myVar\ argument.\ The\ variable\ named\ by\ otherVar\ need\ not\nexist\ at\ the\ time\ of\ the\ call\;\ \ it\ will\ be\ created\ the\ first\ time\ myVar\nis\ referenced,\ just\ like\ an\ ordinary\ variable.\ \ There\ must\ not\ exist\ a\ variable\nby\ the\ name\ myVar\ at\ the\ time\ upvar\ is\ invoked.\ MyVar\ is\ always\ treated\nas\ the\ name\ of\ a\ variable,\ not\ an\ array\ element.\ \ Even\ if\ the\ name\ looks\nlike\ an\ array\ element,\ such\ as\ a(b),\ a\ regular\ variable\ is\ created.\ OtherVar\nmay\ refer\ to\ a\ scalar\ variable,\ an\ array,\ or\ an\ array\ element.\ Upvar\ returns\nan\ empty\ string.\
\nThe\ upvar\ command\ simplifies\ the\ implementation\ of\ call-by-name\nprocedure\ calling\ and\ also\ makes\ it\ easier\ to\ build\ new\ control\ constructs\nas\ Tcl\ procedures.\ For\ example,\ consider\ the\ following\ procedure:\
\nproc \;add2 \;name \;\{
add2\ is\ invoked\ with\ an\ argument\ giving\ the\ name\ of\ a\ variable,\ and\ it\nadds\ two\ to\ the\ value\ of\ that\ variable.\ Although\ add2\ could\ have\ been\ implemented\nusing\ uplevel\ instead\ of\ upvar,\ upvar\ makes\ it\ simpler\ for\ add2\ to\ access\nthe\ variable\ in\ the\ caller&rsquo\;s\ procedure\ frame.\
\n \; \; \;upvar \;\$name \;x
\n \; \; \;set \;x \;\[expr \;\$x+2\]
\n\}
\n
\nnamespace\ eval\ is\ another\ way\n(besides\ procedure\ calls)\ that\ the\ Tcl\ naming\ context\ can\ change.\ It\ adds\na\ call\ frame\ to\ the\ stack\ to\ represent\ the\ namespace\ context.\ This\ means\neach\ namespace\ eval\ command\ counts\ as\ another\ call\ level\ for\ uplevel\ and\nupvar\ commands.\ For\ example,\ info\ level\ 1\ will\ return\ a\ list\ describing\na\ command\ that\ is\ either\ the\ outermost\ procedure\ call\ or\ the\ outermost\nnamespace\ eval\ command.\ Also,\ uplevel\ #0\ evaluates\ a\ script\ at\ top-level\nin\ the\ outermost\ namespace\ (the\ global\ namespace).\
\nIf\ an\ upvar\ variable\nis\ unset\ (e.g.\ x\ in\ add2\ above),\ the\ unset\ operation\ affects\ the\ variable\nit\ is\ linked\ to,\ not\ the\ upvar\ variable.\ \ There\ is\ no\ way\ to\ unset\ an\ upvar\nvariable\ except\ by\ exiting\ the\ procedure\ in\ which\ it\ is\ defined.\ \ However,\nit\ is\ possible\ to\ retarget\ an\ upvar\ variable\ by\ executing\ another\ upvar\ncommand.\ \n
\nUpvar\ interacts\ with\ traces\ in\ a\ straightforward\nbut\ possibly\ unexpected\ manner.\ \ If\ a\ variable\ trace\ is\ defined\ on\ otherVar,\nthat\ trace\ will\ be\ triggered\ by\ actions\ involving\ myVar.\ \ However,\ the\ trace\nprocedure\ will\ be\ passed\ the\ name\ of\ myVar,\ rather\ than\ the\ name\ of\ otherVar.\n\ Thus,\ the\ output\ of\ the\ following\ code\ will\ be\ localVar\ rather\ than\ originalVar:\n \n
\nproc \;traceproc \;\{ \;name \;index \;op \;\} \;\{
If\ otherVar\ refers\ to\ an\ element\ of\ an\ array,\ then\ variable\ traces\ set\nfor\ the\ entire\ array\ will\ not\ be\ invoked\ when\ myVar\ is\ accessed\ (but\ traces\non\ the\ particular\ element\ will\ still\ be\ invoked).\ \ In\ particular,\ if\ the\narray\ is\ env,\ then\ changes\ made\ to\ myVar\ will\ not\ be\ passed\ to\ subprocesses\ncorrectly.\ \n
\n \; \; \;puts \;\$name
\n\}
\nproc \;setByUpvar \;\{ \;name \;value \;\} \;\{
\n \; \; \;upvar \;\$name \;localVar
\n \; \; \;set \;localVar \;\$value
\n\}
\nset \;originalVar \;1
\ntrace \;variable \;originalVar \;w \;traceproc
\nsetByUpvar \;originalVar \;2
\n\}
\n
proc \;decr \;\{varName \;\{decrement \;1\}\} \;\{
\n \; \; \; \;upvar \;1 \;\$varName \;var
\n \; \; \; \;incr \;var \;\[expr \;\{-\$decrement\}\]
\n\}
\n\n
\ \n\ \n
\n\n
\n
\n\n text/html} \ -set mime_type text/html \ -set title en:upvar.n \ -set lang en ::xowiki::Page create ::xowiki::page108 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command is normally used within a namespace eval command to create one or more variables within a namespace. Each variable name is initialized with value. The value for the last variable is optional.
If a variable name does not exist, it is created. In this case, if value is specified, it is assigned to the newly created variable. If no value is specified, the new variable is left undefined. If the variable already exists, it is set to value if value is specified or left unchanged if no value is given. Normally, name is unqualified (does not include the names of any containing namespaces), and the variable is created in the current namespace. If name includes any namespace qualifiers, the variable is created in the specified namespace. If the variable is not defined, it will be visible to the namespace which command, but not to the info exists command.
If the variable command is executed inside a Tcl procedure, it creates local variables linked to the corresponding namespace variables (and therefore these variables are listed by info vars.) In this way the variable command resembles the global command, although the global command only links to variables in the global namespace. If any values are given, they are used to modify the values of the associated namespace variables. If a namespace variable does not exist, it is created and optionally initialized.
A name argument cannot reference an element within an array. Instead, name should reference the entire array, and the initialization value should be left off. After the variable has been declared, elements within the array can be set using ordinary set or array commands.
namespace eval foo {
variable bar 12345
}
Create an array in a namespace: namespace eval someNS {
variable someAry
array set someAry {
someName someValue
otherName otherValue
}
}
Access variables in namespaces from a procedure: namespace eval foo {
proc spong {} {
# Variable in this namespace
variable bar
puts "bar is $bar"
# Variable in another namespace
variable ::someNS::someAry
parray someAry
}
}
} text/html} \ -set mime_type text/html \ -set title en:variable.n \ -set lang en ::xowiki::Page create ::xowiki::page109 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
This command enters the Tcl event loop to process events, blocking the application if no events are ready. It continues processing events until some event handler sets the value of variable varName. Once varName has been set, the vwait command will return as soon as the event handler that modified varName completes. varName must globally scoped (either with a call to global for the varName, or with the full namespace path specification).
In some cases the vwait command may not return immediately after varName is set. This can happen if the event handler that sets varName does not complete immediately. For example, if an event handler sets varName and then itself calls vwait to wait for a different variable, then it may not return for a long time. During this time the top-level vwait is blocked waiting for the event handler to complete, so it cannot return either.
vwait forever
Wait five seconds for a connection to a server socket, otherwise close
the socket and continue running the script: # Initialise the state
after 5000 set state timeout
set server [socket -server accept 12345]
proc accept {args} {
global state connectionInfo
set state accepted
set connectionInfo $args
}
# Wait for something to happen
vwait state
# Clean up events that could have happened
close $server
after cancel set state timeout
# Do something based on how the vwait finished...
switch $state {
timeout {
puts "no connection on port 12345"
}
accepted {
puts "connection: $connectionInfo"
puts [lindex $connectionInfo 0] "Hello there!"
}
}
} text/html} \ -set mime_type text/html \ -set title en:vwait.n \ -set lang en ::xowiki::Page create ::xowiki::page110 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{[[en:#toc]]
The while command evaluates test as an expression (in the same way that expr evaluates its argument). The value of the expression must a proper boolean value; if it is a true value then body is executed by passing it to the Tcl interpreter. Once body has been executed then test is evaluated again, and the process repeats until eventually test evaluates to a false boolean value. Continue commands may be executed inside body to terminate the current iteration of the loop, and break commands may be executed inside body to cause immediate termination of the while command. The while command always returns an empty string.
Note: test should almost always be enclosed in braces. If not, variable
substitutions will be made before the while command starts executing, which
means that variable changes made by the loop body will not be considered
in the expression. This is likely to result in an infinite loop. If test
is enclosed in braces, variable substitutions are delayed until the expression
is evaluated (before each loop iteration), so changes in the variables
will be visible. For an example, try the following script with and without
the braces around $x<10:
set x 0
Example
Read lines from a channel until we get to the end of the stream,
and print them out with a line-number prepended:
while {$x<10} {
puts "x is $x"
incr x
}
set lineCount 0
while {[gets $chan line] >= 0} {
puts "[incr lineCount]: $line"
}
} text/html} \ -set mime_type text/html \ -set title en:while.n \ -set lang en ::xowiki::Page create ::xowiki::page1 -noinit \ -set description {} \ -set nls_language en_US \ -set text {{