TclX(3tcl)
TclX ๐๐
okay bestie, this is the TclX(3tcl) manual page โ the whole extended-Tcl situation, documented in one place. settle in, it's a long one, and we're only on part 1 ๐ซถ
โจ NAME โจ
TclX โ Extended Tcl: the extended command set for Tcl. it's giving "Tcl but it got a glow-up" ๐
๐ SYNOPSIS ๐
package require Tclx
that's it. that's the whole incantation. slay. โจ
๐ธ INTRODUCTION ๐ธ
so this man page has the docs for every single extension that Extended Tcl (TclX) bolts onto Tcl. TclX levels up what Tcl can do by adding brand new commands to it โ and here's the tea โ it does not change the syntax of standard Tcl. not even a little. Extended Tcl is a superset of standard Tcl, and it gets built right alongside the standard Tcl sources. no cap.
Extended Tcl was created by Karl Lehenbauer and Mark Diekhans, and it's freely redistributable for any use without license or fee. iconic behavior, honestly. ๐
Available since 1989 (yes bestie, it's been THAT girl for decades), Extended Tcl โ also known as TclX โ doesn't just add capabilities to Tcl. it has also been the source of many of the capabilities of the baseline Tcl release, including arrays, files, sockets, file events, and date and time handling, among others. main character energy fr fr. ๐
Extended Tcl introduces a set of new commands and a user-extensible library of useful Tcl procedures โ and any one of those can be automatically loaded the very first time something tries to execute it. lazy-loading before it was cool. ๐
The command descriptions are separated into several sections:
- General Commands
- Debugging and Development Commands
- Unix Access Commands
- File Commands
- Network Programming Support
- File Scanning Commands
- Math Commands
- List Manipulation Commands
- Keyed Lists
- String and Character Manipulation Commands
- XPG/3 Message Catalog Commands
- Help Facility
- Tcl Loadable Libraries and Packages
๐ GENERAL COMMANDS ๐
a set of general, useful Tcl commands โ includes a command to kick off an interactive session with Tcl, a facility for tracing execution, and a looping command. the little utility squad. ๐ง
dirsโ this procedure lists the directories in the directory stack. โจ
commandloop ?-async? ?-interactive on | off | tty? ?-prompt1 cmd? ?-prompt2 cmd? ?-endcommand cmd?
creates an interactive command loop that reads commands from stdin and writes results to stdout. command loops are maybe either be blocking or event oriented. bestie this one is so useful for Tcl scripts that don't normally converse interactively with a user through a Tcl command interpreter, but which sometimes want to enter this mode โ maybe for debugging, maybe for user configuration. the command loop terminates on EOF.
the following options are available:
-asyncโ a command handler will be associated withstdin. when input is available onstdin, it will be read and accumulated until a full command is available. that command will then be evaluated. an event loop must be entered for input to be read and processed. โ ๏ธ-interactive on | off | ttyโ enable or disable interactive command mode. in interactive mode, commands are prompted for and the results of comments are printed. the value maybe any boolean value ortty. ifttyis used, interactive mode is enabled ifstdinis associated with a terminal or terminal emulator. the default istty. ๐-prompt1 cmdโ if specified,cmdis used is evaluate and its result used for the main command prompt. if not specified, the command intcl_prompt1is evaluated to output the prompt. note the difference in behavior โcmdresults is used, whiletcl_prompt1outputs. this is to allow for future expansion to command loops that write to other thanstdout. โจ-prompt2 cmdโ if specified,cmdis used is evaluate and its result used for the secondary (continuation) command prompt. if not specified, the command intcl_prompt2is evaluated to output the prompt.-endcommand cmdโ if specified,cmdis evaluated when the command loop terminates.
in interactive mode, the results of set commands with two arguments are not printed.
if SIGINT is configured to generate a Tcl error, it can be used to delete the current command being type without aborting the program in progress. ๐ญ very "oops never mind" of it
coalesce ?-default value? var ?var...?
iterate through one or more specified variable names. the first variable found that actually exists โ return the value of that variable. if none of the variable names are found to exist, return the default value. and if none of the variables exist and the default value wasn't specified using -default, it returns the empty string. first-one-wins energy. ๐
echo ?str ...?
writes zero or more strings to standard output, followed by a newline. simple. cute. does exactly what it says. ๐
infox option
return information about Extended Tcl, or the current application. the following infox command options are available:
versionโ return the version number of Extended Tcl. the version number for Extended Tcl is generated by combining the base version of the standard Tcl code with another number indicating the version of Extended Tcl being used. ๐patchlevelโ return the patchlevel for Extended Tcl.have_fchownโ return1if thefchownsystem call is available. this supports the-fileidoption on thechownandchgrpcommands.have_fchmodโ return1if thefchmodsystem call is available. this supports the-fileidoption on thechmodcommand.have_flockโ return1if theflockcommand defined,0if it is not available.have_fsyncโ return1if thefsyncsystem call is available and thesynccommand will sync individual files.0if it is not available and thesynccommand will always sync all file buffers.have_ftruncateโ return1if theftruncateorchsizesystem call is available. if it is, theftruncatecommand-fileidoption maybe used.have_msgcatsโ return1if XPG message catalogs are available,0if they are not. thecatgetsis designed to continue to function without message catalogs, always returning the default string.have_posix_signalsโ return1if Posix signals are available (blockandunblockoptions available for thesignalcommand).0is returned if Posix signals are not available.have_signal_restartโ return1if restartable signals are available (-restartoption available for thesignalcommand).0is returned if restartable signals are not available.have_truncateโ return1if thetruncatesystem call is available. if it is, theftruncatecommand may truncate by file path.have_waitpidโ return1if thewaitpidsystem call is available and thewaitcommand has full functionality.0if thewaitcommand has limited functionality.appnameโ return the symbolic application name of the current application linked with the Extended Tcl library. the C variabletclAppNamemust be set by the application to return an application specific value for this variable.applongnameโ return a natural language name for the current application. the C variabletclLongAppNamemust be set by the application to return an application specific value for this variable.appversionโ return the version number for the current application. the C variabletclAppVersionmust be set by the application to return an application-specific value for this variable.apppatchlevelโ return the patchlevel for the current application. the C variabletclAppPatchlevelmust be set by the application to return an application-specific value for this variable.
for_array_keys var array_name code
this procedure performs a foreach-style loop for each key in the named array. the break and continue statements work as with foreach. so yes bestie, you can bail out mid-loop. ๐
for_recursive_glob var dirlist globlist code
this procedure performs a foreach-style loop over recursively matched files. all directories in dirlist are recursively searched (breadth-first), comparing each file found against the file glob patterns in globlist. for each matched file, the variable var is set to the file path and code is evaluated. symbolic links are not followed. ๐ซ๐
loop var first limit ?increment? body
loop is a looping command, similar in behavior to the Tcl for statement โ except that the loop statement achieves substantially higher performance and is easier to code when the beginning and ending values of a loop are known, and the loop variable is to be incremented by a known, fixed amount every time through the loop. glow-up of a for loop honestly. โจ
the var argument is the name of a Tcl variable that will contain the loop index. the loop index is set to the value specified by first. the Tcl interpreter is invoked upon body zero or more times, where var is incremented by increment every time through the loop, or by one if increment is not specified. increment can be negative, in which case the loop will count downwards. ๐ป
when var reaches limit, the loop terminates without a subsequent execution of body. for instance, if the original loop parameters would cause loop to terminate โ say first was one, limit was zero and increment was not specified or was non-negative โ body is not executed at all and loop returns. zero iterations, no problem. ๐
the first, limit and increment are integer expressions. they are only evaluated once at the beginning of the loop. ๐ซถ
if a continue command is invoked within body then any remaining commands in the current execution of body are skipped, as in the for command. if a break command is invoked within body then the loop command will return immediately. loop returns an empty string. ๐
more parts coming, bestie โ do not close the group chat ๐
popdโ this one pops the top directory entry right off the directory stack and makes it your current directory. swoosh. new home unlocked ๐pushd?dir?โ pushes the current directory onto the directory stack and thencds into the directory you named. If you don't name one? it still pushes the current directory but stays exactly where it is. no moving. ๐ซถrecursive_globdirlistgloblistโ returns a list of recursively matched files. Every directory in dirlist gets searched recursively (breadth-first, bestie) and every file it finds gets compared against the file glob patterns in globlist. Symbolic links are not followed. periodt.showproc?procname ...?โ lists the definition of the procedures you name, loading them first if they aren't already loaded. Name zero procedures and you get the definitions of every currently loaded procedure. the entire friend group, exposed. ๐try_evalcodecatch?finally?โ evaluates code in the current context.
If an error goes down during that evaluation and catch isn't empty, then catch gets evaluated to handle the error. The result of the command, with the error message living inside it, gets stored in a global variable called errorResult. The global variables errorResult, errorInfo and errorCode get imported into the current scope automatically โ there is literally no need to run a global command, it's already done for you. The result of the catch command becomes the result of the try_eval command. And if you want to keep an error going after catch got evaluated, you run this:
error $errorResult $errorCode $errorInfo
If the finally argument is supplied and it's not empty, it gets evaluated after code and catch have both been evaluated. If an error happens while finally is being evaluated, that error becomes the result of the try_eval command. Otherwise the result of either code or catch is preserved, exactly as described above. ๐ฆ
๐ DEBUGGING AND DEVELOPMENT COMMANDS ๐
This section is all about the commands and procedures that are useful for developing and debugging Tcl scripts. your little toolbox for when things are โจnot workingโจ
cmdtracelevel|on?noeval??notruncate??procs??fileid??command cmd?โ prints a trace statement for all commands executed at depth of level or below (level1is the top level). If you sayoninstead, then all commands at any level get traced. These are the options you can pass:noevalโ causes arguments to be printed unevaluated. Withnoevalthe arguments get printed before evaluation. Otherwise they get printed afterwards.
If the command line is longer than 60 characters, it gets truncated to 60 and a "..." gets postpended to show there was more output than got displayed. If an evaluated argument contains a space, the whole argument gets enclosed inside braces ({}) so you can visually tell where one argument stops and the next one starts. ๐
notruncateโ disables the truncation of commands and evaluated arguments.procsโ turns on tracing of procedure calls only. Commands that aren't procedure calls (i.e. calls to commands written in C, C++ or some object-compatible language) don't get traced when this option is specified. This one is especially useful for greatly reducing the output ofcmdtracewhile you're debugging.fileidโ this is a file id as returned by theopencommand. If you specify it, the trace output gets written to that file instead of stdout. A stdio buffer flush happens after every single line is written, so the trace can be monitored externally or give you useful info when debugging problems that cause core dumps. ๐commandcmdโ calls the specified command cmd on each command execution instead of tracing to a file. See the description of the functionality below. This option may not be specified with afileid.
The most common use of this command is to turn on tracing to a file during development, so if a failure happens, a trace is already sitting there when you need it. Command tracing slows down the execution of your code, so it should be removed once the code is debugged. This next command enables tracing to a file for the rest of the program:
cmdtrace on [open cmd.log w]
The command option makes a user-specified trace command get called for every command executed. Before evaluation, the following arguments get appended to it:
commandโ a string containing the text of the command, before any argument substitution.argvโ a list of the final argument information that will be passed to the command after command, variable and backslash substitution.evalLevelโ theTcl_Evalcall level.procLevelโ the procedure call level.
Your command should be constructed so it'll still work if additional arguments get added in the future. It's suggested that the command be a proc with the final argument being args.
Tracing gets turned off while the command is being executed. The values of the errorInfo and errorCode variables get saved and restored when the command returns. It's the command's responsibility to preserve all other state.
If an error happens during the execution of the command, an error message gets dumped to stderr and the tracing gets disabled. The underlying mechanism that this functionality is built on does not support returning an error to the interpreter. so like. it just can't.
cmdtrace offโ turns off all tracing.cmdtrace depthโ returns the current maximum trace level, or zero if tracing is disabled.edprocs?proc...?โ writes the named procedures (or all currently defined procedures if you name none) to a temporary file, calls an editor on it (whichever one theEDITORenvironment variable says, orviif none is specified), then sources the file back in if it changed. โจprofile?-commands??-eval?on,profile offarrayVarโ collects a performance profile of a Tcl script. It gathers data at the Tcl procedure level โ how many calls a procedure got, plus the amount of real and CPU time used. Time is also collected for the global context. The procedure data gets collected by bucketing it based on the procedure call stack, which lets you figure out how much time is spent in a particular procedure in each of its calling contexts. ๐
The on option enables profile data collection. If the -commands option is specified, data on all commands within a procedure is collected as well as procedures. Multiple occurrences of a command within a procedure are not distinguished, but the data may still be useful for analysis.
The off option turns off profiling and moves the collected data into the array arrayVar. The array is addressed by a list containing the procedure call stack. Element zero is the top of the stack, the procedure that the data is for. The data in each entry is a list consisting of the procedure call count and the real time and CPU time in milliseconds spent in the procedure (but not any procedures it calls). The list is in the form {count real cpu}.
Normally the variable scope stack is what's used when reporting where time is spent, so upleveled code gets reported in the context it was executed in, not the context the uplevel was called in. If you specify -eval, the procedure evaluation (call) stack is used instead of the procedure scope stack, so upleveled code gets reported in the context of the procedure that did the uplevel.
A Tcl procedure called profrep is supplied for reducing the data and producing a report.
On Windows, the profile command only reports elapsed real time. CPU time is not available and gets reported as zero. ๐ญ
profrepprofDataVarsortKey?outFile??userTitle?โ generates a report from data collected by theprofilecommand. ProfDataVar is the name of the array containing the data returned byprofile. SortKey says which data value to sort by, and it should be one of"calls","cpu"or"real". OutFile is the name of the file to write the report to; if it's omitted, stdout is assumed. UserTitle is an optional title line to add to the output.
Listed with indentation below each procedure or command is the procedure call stack. The first indented line is the procedure that invoked the reported procedure or command. The next line is the procedure that invoked the procedure above it, and so on. If no indented procedures are shown, then the procedure or command was called from the global context. Time actually spent in the global context is listed on a line labeled <global>. Upleveled code is reported in the context that it was executed in, not the context that the uplevel was called in.
saveprocsfileName?proc...?โ saves the definition of the named procedure (or all currently defined procedures if none is specified) to the named file. ๐
๐ UNIX ACCESS COMMANDS ๐
These commands give you access to a whole bunch of basic Unix facilities โ process handling, date and time processing, signal handling, and executing commands through the shell. the classics, fr fr ๐ง
alarmsecondsโ tells the system to send aSIGALRMsignal in the specified number of seconds. This is a floating point number, so fractions of a second are fair game. If seconds is0.0, any previous alarm request is canceled. Only one alarm at a time may be active, and the command returns the number of seconds left in the previous alarm. On systems without thesetitimersystem call, seconds gets rounded up to an integer number of seconds.
The alarm command is not available on Windows. ๐
execl ?-argv0 argv0? prog ?arglist?โ โจ bestie this is the full send command. It does anexecl, meaning it replaces the current program (either Extended Tcl itself, or an application that has Extended Tcl embedded into it) withprog, and passes along the arguments sitting in the listarglist. Like, the old process is gone, no take-backs, periodt.-argv0โ this option specifies thatargv0is what gets passed to the program asargv [0], instead ofprog. Little identity swap, iykyk. ๐
โ ๏ธ Real talk: if you're usingexeclinside a Tk application and it fails, you may not do anything that accesses the X server, or the X server will hit you with aBadWindowerror. And yes, that includes executing the Tk version of theexitcommand. The suggested way to abort Tk applications after anexeclfailure is this:
kill [id process]
- On Windows, where the
forkcommand isn't available,execlstarts a new process and returns the process id. ๐ฆ
chroot dirnameโ changes the root directory todirnameby invoking the POSIXchroot(2)system call. Honestly kind of iconic and also kind of terrifying. It only succeeds if you're running as root. ๐forkโ forks the current Tcl process, fr fr.forkreturns zero to the child process, and returns the process number of the child to the parent process. If the fork fails, a Tcl error is generated. ๐ญ- So here's the tea: if an
execlis not going to be performed before the child process does output, or if acloseanddupsequence is going to be performed onstdoutorstderr, then you should issue aflushagainststdout,stderrand any other open output file before doing the fork. Otherwise, characters from the parent process that are still chillin' in the buffers will get output by both the parent and the child processes. ๐
- So here's the tea: if an
โ ๏ธ And if you're forking in a Tk based application, you mustexeclbefore doing any window operations in the child, or you'll catch aBadWindowerror from the X server.
- The
forkcommand is not available on Windows. Sorry babe. ๐
id optionsโ okay so this one is the ID multi-tool: a way to get, set and convert user, group and process ids. It has these options:id user ?name?id userid ?uid?โ sets the real and effective user ID tonameoruid, if that name (or uid) is valid and permissions allow it. If the name (or uid) isn't specified, the current name (or uid) is returned. ๐id convert userid uidid convert user nameโ converts a user ID number to a user name, or the other way around. ๐id group ?name?id groupid ?gid?โ sets the real and effective group ID tonameorgid, if that name (or gid) is valid and permissions allow it. If the name (or gid) isn't specified, the current group name (or gid) is returned.id groupsid groupidsโ return the current group access list of the process. The optiongroupsgives you group names, andgroupidsgives you the id numbers.id convert groupid gidid convert group nameโ converts a group ID number to a group name, or vice versa.id effective userid effective useridโ return the effective user name, or the effective user ID number, respectively.id effective groupid effective groupidโ return the effective group name, or the effective group ID number, respectively.id effective groupidsโ return all of the groupids the user is a member of. ๐ซถid hostโ return the hostname of the system the program is running on.id processโ return the process ID of the current process.id process parentโ return the process ID of the parent of the current process.id process groupโ return the process group ID of the current process.id process group setโ set the process group ID of the current process to its process ID.id hostโ returns the standard host name of the machine the process is executing on. (Yes, it's listed twice in the original, and honestly? Host name so nice they said it twice. ๐)- On Windows, only the
hostandprocessoptions are implemented. ๐
kill ?-pgroup ?signal? idlistโ sends a signal to each process in the listidlist, if permitted.signal, if present, is the signal number or the symbolic name of the signal โ check thesignalsystem call manual page for those. The leadingSIGis optional when you specify the signal by its symbolic name. The default forsignois15,SIGTERM.-pgroupโ if this is specified, the numbers inidlistare taken as process group ids, and the signal gets sent to all of the processes in that process group. A process group id of0specifies the current process group. ๐ฏ- On Windows, the
killcommand is capable of terminating a process, but not of sending an arbitrary signal. ๐
link ?-sym? srcpath destpathโ creates a directory entry,destpath, linking it to the existing filesrcpath. If-symis specified, a symbolic link is created rather than a hard link. (The-symoption is only available on systems that support symbolic links, so vibe check your OS first.)- The
linkcommand is not available on Windows. Use the Tcl 8.4+file linkcommand instead. โจ
- The
nice ?priorityincr?โ change or return the process priority. Ifpriorityincris omitted, the current priority is returned. Ifpriorityincris positive, it gets added to the current priority level, up to a system defined maximum (normally19).- Negative
priorityincrvalues cumulatively increase the program's priority, down to a system defined minimum (normally-19). But heads up: increasing priority with negative niceness values will only work for the superuser. ๐ - The new priority is returned.
- The
nicecommand is not available on Windows.
- Negative
readdir ?-hidden? dirPathโ returns a list containing the contents of the directorydirPath. The directory entries"."and".."are not returned. ๐- On Windows,
-hiddenmaybe be specified to include hidden files in the result. This flag is ignored on Unix systems.
- On Windows,
signal ?-restart? action siglist ?command?โ the whole signal-handling situation, and it's giving main character energy. Read the warning first, bestie:
โ ๏ธ Warning: If signals are being used as an event source (a trap action), rather than generating an error to terminate a task, one must use the-restartoption. This causes a blocked system call, such asreadorwaitpid, to be restarted rather than generate an error. Failure to do this may result in unexpected errors when a signal arrives while in one of these system calls. When available, the-restartoption can prevent this problem.
-restartโ if specified, restart blocking system calls rather than generating an error. The signal will be handled once the Tcl command that issued the system call completes. Heads up though: the-restartoption is not available on all operating systems, and using it will generate an error when it isn't supported. Useinfox have_signal_restartto check for availability. ๐
So: specify the action to take when a Unix signal is received by Extended Tcl, or by a program that embeds it. Siglist is a list of either the symbolic or numeric Unix signal (the SIG prefix is optional). Action is one of the following things to do when the signal shows up. To specify all modifiable signals, use * โ and note that this will not include SIGKILL and SIGSTOP, because they can not be modified. ๐
defaultโ perform the system default action when the signal is received (see thesignalsystem call documentation).ignoreโ ignore the signal. Not me pretending I didn't see it. ๐errorโ generate a catchable Tcl error. It will be as if the command that was running returned an error. The error code will be in the form:
POSIX SIG signame
For the death of child signal, signame will always be SIGCHLD, rather than SIGCLD, to allow writing portable code. ๐ง
trapโ when the signal occurs, executecommandand continue execution if an error is not returned bycommand. The command will be executed in the global context. The command will be edited before execution, replacing occurrences of"%S"with the signal name. Occurrences of"%%"result in a single"%". This editing occurs just before the trap command is evaluated. If an error is returned, then follow the standard Tcl error mechanism. Oftencommandwill just do anexit. ๐getโ retrieve the current settings of the specified signals. A keyed list will be returned where the keys are one of the specified signals and the values are a list consisting of the action associated with the signal, a0if the signal may be delivered (not blocked) and a1if it is blocked, and a flag indicating if restarting of system calls is specified. The actions maybe one ofdefault,ignore,errorortrap. If the action istrap, the third element is the command associated with the action. The actionunknownis returned if a non-Tcl signal handler has been associated with the signal. ๐setโ set signals from a keyed list in the format returned by theget. For this action,siglistis the keyed list of signal state. Signals with an action ofunknownare not modified.blockโ block the specified signals from being received. (Posix systems only). ๐ซunblockโ allow the specified signal to be received. Pending signals will not occur. (Posix systems only).
The signal action will remain enabled after the specified signal has occurred. The exception to this is SIGCHLD on systems without Posix signals. For these systems, SIGCHLD is not be automatically re-enabled. After a SIGCHLD signal is received, a call to wait must be performed to retrieve the exit status of the child process before issuing another signal SIGCHLD ... command. For code that is to be portable between both types of systems, use this approach. ๐ธ
Signals are not processed until after the completion of the Tcl command that is executing when the signal is received. Periodt. If an interactive Tcl shell is running, then the SIGINT will be set to error, and non-interactive Tcl sessions leave SIGINT unchanged from when the process started โ normally default for foreground processes and ignore for processes in the background. ๐
sleep secondsโ okay bestie, this makes the Extended Tcl process nap for seconds seconds. If seconds is specified as a decimal number, it's truncated to an integer value. ๐ด๐คsystem cmdstr1 ?cmdstr2...?โ this one concatenatescmdstr1,cmdstr2etc with space separators (see theconcatcommand) into a single command, then evaluates that command using the standard system shell. On Unix systems, that's/bin/sh, and on Windows it'scommand.com. The exit code of the command is returned. ๐ฅ
This command is lowkey different from the exec command because system doesn't return the executed command's standard output as the result string, and system goes through the Unix shell to provide wild card expansion, redirection, etc, as is normal from an sh command line. So if you need shell magic, this is your girl. ๐โจ
sync ?fileId?โ if fileId is not specified, or if it is and this system does not support thefsyncsystem call, it issues asyncsystem call to flush all pending disk output. If fileId is specified and the system does support thefsyncsystem call, it issues anfsyncon the file corresponding to the specified Tcl fileId to force all pending output to that file out to the disk. ๐พ
If fileId is specified, the file must be writable. A flush will be issued against the fileId before the sync. ๐ฝ
The infox have_fsync command can be used to determine if "sync fileId" will do a sync or a fsync. iykyk.
timesโ returns a list containing the process and child execution times in the form:
utime stime cutime cstime
Also see the times(2) system call manual page. The values are in milliseconds. โฑ๏ธ
umask ?octalmask?โ sets file-creation mode mask to the octal value of octalmask. If octalmask is omitted, the current mask is returned. ๐wait ?-nohang? ?-untraced? ?-pgroup? ?pid?โ waits for a process created with theexeclcommand to terminate, either due to an untrapped signal or call toexitsystem call. If the process id pid is specified, they wait on that process, otherwise wait on any child process to terminate. ๐
If -nohang is specified, then don't block waiting on a process to terminate. If no process is immediately available, return an empty list. If -untraced is specified then the status of child processes that are stopped, and whose status has not yet been reported since they stopped, are also returned. If -pgroup is specified and pid is not specified, then wait on any child process whose process group ID is they same as the calling process. If pid is specified with -pgroup, then it is take as a process group ID, waiting on any process in that process group to terminate. ๐ซถ
wait returns a list containing three elements: The first element is the process id of the process that terminated. If the process exited normally, the second element is EXIT', and the third contains the numeric exit code. If the process terminated due to a signal, the second element is SIG', and the third contains the signal name. If the process is currently stopped (on systems that support SIGSTP), the second element is STOP', followed by the signal name. ๐
Note that it is possible to wait on processes to terminate that were create in the background with the exec command. However, if any other exec command is executed after the process terminates, then the process status will be reaped by the exec command and will not be available to the wait command. ๐
On systems without the waitpid system call, the -nohang, -untraced and -pgroup options are not available. The infox have_waitpid command maybe use to determine if this functionality is available. ๐ง
โจ FILE COMMANDS โจ
These commands provide extended file access and manipulation. This includes searching ASCII-sorted data files, copying files, duplicating file descriptors, control of file access options, retrieving open file status, and creating pipes with the pipe system call. Also linking files, setting file, process, and user attributes and truncating files. An interface to the select system call is available on Unix systems that support it. ๐๏ธ๐
It should be noted that Tcl file I/O is implemented on top of the stdio library. By default, the file is buffered. When communicating to a process through a pipe, a flush command should be issued to force the data out. Alternatively, the fcntl command may be used to set the buffering mode of a file to line-buffered or unbuffered. ๐ฐ
bsearch fileId key ?retvar? ?compare_proc?โ search an opened file fileId containing lines of text sorted into ascending order for a match. Key contains the string to match. If retvar is specified, then the line from the file is returned in retvar, and the command returns1if key was found, and0if it wasn't. If retvar is not specified or is a null name, then the command returns the line that was found, or an empty string if key wasn't found. ๐
By default, the key is matched against the first white-space separated field in each line. The field is treated as an ASCII string. If compare_proc is specified, then it defines the name of a Tcl procedure to evaluate against each line read from the sorted file during the execution of the bsearch command. Compare_proc takes two arguments, the key and a line extracted from the file. The compare routine should return a number less than zero if the key is less than the line, zero if the key matches the line, or greater than zero if the key is greater than the line. The file must be sorted in ascending order according to the same criteria compare_proc uses to compare the key with the line, or erroneous results will occur. ๐ง
This command does not work on files containing binary data (bytes of zero). ๐ซ
channelfd channelโ get the unix file descriptor, an integer, for channel using theTcl_GetChannelHandleAPI. On any error the return value-1. ๐ฏ
The channelfd command is not available on Windows. ๐ชโ
chmod [-fileid] mode filelistโ set permissions of each of the files in the list filelist to mode, where mode is an absolute numeric mode or symbolic permissions as in the UNIXchmod(1)command. The numeric mode argument is assumed octal by default (e.g.733), unless otherwised specified using an explicit radix indicator (e.g.0d493). ๐ง
If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems. Use the infox have_fchmod command to determine if this functionality is available. ๐
The chmod command is not available on Windows. ๐ชโ
chown [-fileid] owner | {owner group} filelistโ set owner of each file in the list filelist to owner, which can be a user name or numeric user id. If the first parameter is a list, then the owner is set to the first element of the list and the group is set to the second element. Group can be a group name or numeric group id. If group is{}, then the file group will be set to the login group of the specified user. ๐
If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems. Use the infox have_fchown command to determine if this functionality is available. ๐
The chown command is not available on Windows. ๐ชโ
chgrp [-fileid] group filelistโ set the group id of each file in the list filelist to group, which can be either a group name or a numeric group id. ๐ฅ
If the option -fileid is specified, filelist is a list of open file identifiers rather than a list of file names. This option is not available on all Unix systems. Use the infox have_fchown command to determine if this functionality is available. ๐
The chgrp command is not available on Windows. ๐ชโ
dup fileId ?targetFileId?โ duplicate an open file. A new file id is opened that addresses the same file as fileId. ๐ช
If targetFileId is specified, the the file is dup to this specified file id. Normally this is stdin, stdout, or stderr. The dup command will handle flushing output and closing this file. The new file will be buffered, if its needs to be unbuffered, use the fcntl command to set it unbuffered. ๐
If fileId is a number rather than a Tcl file id, then the dup command will bind that file to a Tcl file id. This is useful for accessing files that are passed from the parent process. The argument ?targetFileId? is not valid with this operation. ๐
On Windows, only stdin, stdout, or stderr or a non-socket file handle number maybe specified for targetFileId. The dup command does not work on sockets on Windows. ๐ช๐
fcntl fileId attribute ?value?โ this command either sets or clears a file option or returns its current value. If value is not specified, then the current value of attribute is returned. All values are boolean. Some attributes maybe only be gotten, not modified. The following attributes may be specified: โ๏ธRDONLYโ The file is opened for reading only. (Get only) ๐WRONLYโ The file is opened for writing only. (Get only) โ๏ธRDWRโ The file is opened for reading and writing. (Get only) ๐READโ If the file is readable. (Get only). ๐WRITEโ If the file is writable. (Get only). ๐๏ธAPPENDโ The file is opened for append-only writes. All writes will be forced to the end of the file. (Get or set). โNONBLOCKโ The file is to be accessed with non-blocking I/O. See thereadsystem call for a description of how it affects the behavior of file reads. ๐ฆCLOEXECโ Close the file on an process exec. If theexeclcommand or some other mechanism causes the process to do an exec, the file will be closed if this option is set. ๐
NOBUFโ bestie, this file is not buffered, like at all. No buffering for it, periodt. ๐LINEBUFโ output on this file is line buffered โจ the buffer gets flushed the moment a newline is written, when the buffer fills up, or when input is requested. It's giving considerate. ๐KEEPALIVEโ keeps a socket connection alive ๐ซถ. If SIGPIPE is enabled, then it gets sent when the connection breaks and data is written to the socket. If SIGPIPE is ignored instead, an error comes back on the write. Heads up: this attribute is valid only on sockets. And for the record, SIGPIPE is ignored by default in Tcl.
Okay so real talk: NONBLOCK, NOBUF and LINEBUF are all just hanging around for compatibility with older scripts ๐ โ the fconfigure command is the preferred method of getting and setting these attributes. iykyk.
๐จ Also: theAPPENDandCLOEXECoptions are not available on Windows. Not the vibe, but it's the law.
flock
flock options fileId ?start? ?length? ?origin?
This one places a lock ๐ on all or part of the file specified by fileId. Whether that lock is advisory or mandatory depends on the mode bits of the file. The lock gets placed beginning at relative byte offset start for length bytes. If start or length is omitted or empty, zero is assumed. If length is zero, then the lock always extends to the end of file โ even if the file grows ๐.
If origin is "start", then the offset is relative to the beginning of the file. If it's "current", it's relative to the current access position in the file. If it's "end", then it's relative to the end-of-file (a negative is before the EOF, a positive is after). If origin is omitted, then start is assumed.
The following options are recognized:
-readโ place a read lock on the file. Multiple processes may be accessing the file with read-locks ๐ค.-writeโ place a write lock on the file. Only one process may be accessing a file if there's a write lock ๐.-nowaitโ if specified, the process will not block if the lock can't be obtained. With this option, the command returns1if the lock is obtained and0if it isn't.
Peep your system's fcntl system call documentation for the full tea on how file locking actually behaves ๐ต. And if you're locking ranges of a file, it's genuinely best to use unbuffered file access (see the fcntl command).
๐ flock is not available on Windows 95. It is available on Windows NT.
for_file
for_file var filename code
This procedure implements a loop over the contents of a file ๐ธ. For each line in filename, it sets var to the line and executes code.
The break and continue commands work exactly like they do with foreach โ no notes. ๐
For example, the command
for_file line /etc/passwd {echo $line}
would echo all the lines in the password file. Ate. ๐ฅ
funlock
funlock fileId ?start? ?length? ?origin?
Removes a lock from a file that was previously placed with the flock command ๐ซถ. The arguments are the same as for flock โ go see that command for more details.
๐ funlock is not available on Windows 95. It is available on Windows NT.
fstat
fstat fileId ?item? | ?stat arrayvar?
Obtain status information about an open file ๐. The following keys are used to identify data items:
atimeโ the time of last access.ctimeโ the time of last file status change.devโ the device containing a directory for the file. This value uniquely identifies the file system that contains the file.gidโ the group ID of the file's group.inoโ the inode number. This field uniquely identifies the file in a given file system.modeโ the mode of the file (see themknodsystem call).mtimeโ time when the data in the file was last modified.nlinkโ the number of links to the file.sizeโ the file size in bytes.ttyโ if the file is associated with a terminal, then1, otherwise0.typeโ the type of the file in symbolic form, which is one of the following values:file,directory,characterSpecial,blockSpecial,fifo,link, orsocket.uidโ the user ID of the file's owner.
If one of these keys is specified as item, then that data item is returned ๐ฏ.
If stat arrayvar is specified, then the information is returned in the array arrayvar. Each of the above keys indexes an element of the array containing the data.
If only fileId is specified, the command returns the data as a keyed list โจ.
The following values may be returned only if explicitly asked for โ they will not be returned with the array or keyed list forms ๐ โโ๏ธ:
remotehostโ iffileIdis a TCP/IP socket connection, then a list is returned with the first element being the remote host IP address. If the remote host name can be found, it's returned as the second element of the list. The remote host IP port number is the third element.localhostโ iffileIdis a TCP/IP socket connection, then a list is returned with the first element being the local host IP address. If the local host name can be found, it's returned as the second element of the list. The local host IP port number is the third element.
ftruncate
ftruncate [-fileid] file newsize
Truncate a file so it has a length of at most newsize bytes โ๏ธ.
If the option -fileid is specified, then file is an open file identifier, otherwise it's a file path.
โ ๏ธ This command is not available or not fully functional if the underlying operating system support isn't available. The commandinfox have_truncatewill tell you if this command may truncate by file path. The commandinfox have_ftruncatewill tell you if this command may truncate by file id. Always vibe check first ๐ง.
๐ The -fileid option is not available on Windows.
lgets
lgets fileId ?varName?
Reads the next Tcl list from the file given by fileId and discards the terminating newline character ๐. This is different from the gets command because it reads Tcl lists rather than lines, okay? If the list contains newlines or binary data, then that newline or those bytes of zero get returned as part of the result. Only a newline that is not quoted as part of the list indicates the end of the list. There's no corresponding command for outputting lists, because puts already does that correctly ๐
.
If varName is specified, then the line is placed in the variable by that name and the return value is a count of the number of characters read (not including the newline). If the end of the file is reached before reading any characters, then -1 is returned and varName is set to an empty string. If varName is specified and an error occurs, whatever data was read will be returned in the variable โ however, the resulting string may not be a valid list ๐ญ. Not ideal.
If varName is not specified, then the return value will be the line (minus the newline character), or an empty string if the end of the file is reached before reading any characters. An empty string will also be returned if a line contains no characters except the newline, so eof may have to be used to figure out what really happened. Sneaky. ๐
You can use lgets to read and write lists containing binary data, but translation must be set to lf or the data maybe corrupted. Do not skip that step. ๐
And yeah โ lgets is currently supported on non-blocking files. โจ
pipe
pipe ?fileId_var_r fileId_var_w?
Create a pipe ๐. If fileId_var_r and fileId_var_w are specified, then pipe will set the variable named fileId_var_r to contain the fileId of the side of the pipe that was opened for reading, and fileId_var_w will contain the fileId of the side of the pipe that was opened for writing.
If the fileId variables are not specified, then a list containing the read and write fileIds is returned as the result of the command. Easy. ๐ซถ
read_file
read_file ?-nonewline? fileName
read_file fileName numBytes
This procedure reads the file fileName and returns the contents as a string ๐. If -nonewline is specified, then the last character of the file is discarded if it's a newline. The second form specifies exactly how many bytes will be read and returned โ unless there are fewer than numBytes bytes left in the file, in which case all the remaining bytes are returned. Take what you can get. ๐
select
select readfileIds ?writefileIds? ?exceptfileIds? ?timeout?
This command lets an Extended Tcl program wait on zero or more files being ready for reading, being ready for writing, having an exceptional condition pending, or waiting for a timeout period to expire โณ. readFileIds, writeFileIds, exceptFileIds are each lists of fileIds, as returned from open, to query. An empty list ({}) may be specified if a category isn't being used.
The files specified by the readFileIds list are checked to see if data is available for reading. The writeFileIds are checked to see if the specified files are clear for writing. The exceptFileIds are checked to see if an exceptional condition has occurred (typically, an error) ๐. The write and exception checking is most useful on devices, however the read checking is very useful when communicating with multiple processes through pipes. Select considers data pending in the stdio input buffer for read files as being ready for reading โ the files do not have to be unbuffered. ๐ฆ
Timeout is a floating point timeout value, in seconds. If an empty list is supplied (or the parameter is omitted), then no timeout is set. If the value is zero, then the select command functions as a poll of the files, returning immediately even if none are ready. No waiting around. ๐
If the timeout period expires with none of the files becoming ready, then the command returns an empty list. Otherwise the command returns a list of three elements, and each of those elements is a list of the fileIds that are ready in the read, write and exception classes. If none are ready in a class, then that element will be the null list. For example:
select {file3 file4 file5} {file6 file7} {} 10.5
could return
...and the pattern list keeps going, like
{file3 file4} {file6} {}
or maybe
file3 {} {}
whatever your little heart desires, bestie ๐
Heads up for the Windows girlies: on Windows, only sockets can be used with theselectcommand. Pipes, as returned by theopencommand, are not supported. Not a vibe. ๐ซ๐ช
write_file fileName string ?string...?โ writes the strings you give it into the file namedfileName. That's it, that's the whole job, and it does it flawlessly ๐
๐ NETWORK PROGRAMMING SUPPORT ๐
TclX is here to be the hype squad for Tcl's socket command โ it gives you the extra functionality that command doesn't have on its own. The host_info command is your go-to for getting info about a host, whether you know it by name or by IP address. On top of that, fstat and fcntl hand you options for querying and controlling connected sockets. And if you wanna know the host name of the local system, you hit up the id host command. iykyk โจ
host_info option hostโ pull information about an Internet host. Thehostargument can be either a host name or an IP address. Iconic flexibility fr fr ๐ฆ
The following subcommands are recognized (they go in the option slot):
addressesโ returns the list of IP addresses forhost. ๐official_nameโ returns the official name forhost. ๐aliasesโ returns the list of aliases forhost. Quick note bestie: these are IP number aliases, not DNS CNAME aliases โ go peek atifconfig(2)if you want the tea. ๐ซ
๐ FILE SCANNING COMMANDS ๐
Okay so these commands are the moment. They give you a facility to scan files, matching lines of the file against regular expressions and executing Tcl code the second something matches. With this, you can use Tcl to do the sort of file processing that's traditionally done with awk. And honestly? Since Tcl's approach is more declarative, some scripts that are genuinely painful to write in awk are justโฆ simple to code in Tcl. Nature is healing ๐ธ
File scanning in Tcl centers around the concept of a scan context. A scan context contains one or more match statements, which associate regular expressions to scan for with Tcl code to be executed when those expressions are matched. Cute, organized, no notes ๐
scancontext ?option?โ manages file scan contexts. A scan context is a collection of regular expressions and commands to execute when that regular expression matches a line of the file. A context may also have a single default match, to be applied against lines that don't match any of the regular expressions. Multiple scan contexts may be defined, and they may be reused on multiple files. A scan context is identified by a context handle.
The scancontext command takes the following forms:
scancontext createโ creates a new scan context. You use thescanmatchcommand to define patterns in the context. Acontexthandleis returned, which the Tcl programmer uses to refer to the newly created scan context in calls to the Tcl file scanning commands. โจscancontext delete contexthandleโ deletes the scan context identified bycontexthandle, and frees all of the match statements and compiled regular expressions associated with that context. Poof, gone, bye ๐scancontext copyfile contexthandle ?filehandle?โ sets or returns the file handle that unmatched lines are copied to. (Seescanfile.)- If
filehandleis omitted, the copy file handle is returned. ๐ - If no copy file is associated with the context,
{}is returned. - If a file handle is specified, it becomes the copy file for this context.
- If
filehandleis{}, then it removes any copy file specification for the context.
- If
scanfile ?-copyfile copyFileId? contexthandle fileIdโ scans the file specified byfileId, starting from the current file position. It checks all patterns in the scan context specified bycontexthandleagainst it, executing the match commands corresponding to the patterns that matched. ๐ฏ
If the optional -copyfile argument is specified, the next argument is a file ID to which all lines not matched by any pattern (excluding the default pattern) are to be written. If the copy file is specified with this flag โ instead of by using the scancontext copyfile command โ the file is disassociated from the scan context at the end of the scan.
Fr fr bestie, this command does not work on files containing binary data (bytes of zero). Like, don't even try it ๐
scanmatch ?-nocase? contexthandle ?regexp? commandsโ specifies Tcl commands to be evaluated whenregexpis matched by ascanfilecommand. The match is added to the scan context specified bycontexthandle. Any number of match statements may be specified for a given context.regexpis a regular expression (see theregexpcommand). If-nocaseis specified as the first argument, the pattern is matched regardless of alphabetic case โ case? never heard of her ๐ฅ
If regexp is not specified, then a default match is specified for the scan context. The default match will be executed when a line of the file does not match any of the regular expressions in the current scancontext.
The array matchInfo is available to the Tcl code that is executed when an expression matches (or defaults). It contains information about the file being scanned and where within it the expression was matched. ๐
matchInfo is local to the top level of the match command unless declared global at that level by the Tcl global command. If it is to be used as a global, it must be declared global before scanfile is called (since scanfile sets the matchInfo before the match code is executed, a subsequent global will override the local variable). The following array entries are available:
matchInfo(line)โ contains the text of the line of the file that was matched. ๐matchInfo(offset)โ the byte offset into the file of the first character of the line that was matched.matchInfo(linenum)โ the line number of the line that was matched. This is relative to the first line scanned, which is usually, but not necessarily, the first line of the file. The first line is line number one. 1๏ธโฃmatchInfo(context)โ the context handle of the context that this scan is associated with.matchInfo(handle)โ the file id (handle) of the file currently being scanned.matchInfo(copyHandle)โ the file id (handle) of the file specified by the-copyfileoption. This element does not exist if-copyfilewas not specified. ๐matchInfo(submatch0)โ will contain the characters matching the first parenthesized subexpression. The second will be contained insubmatch1, etc.matchInfo(subindex0)โ will contain a list of the starting and ending indices of the string matching the first parenthesized subexpression. The second will be contained insubindex1, etc.
All scanmatch patterns that match a line will be processed in the order in which their specifications were added to the scan context. The remainder of the scanmatch pattern-command pairs may be skipped for a file line if a continue is executed by the Tcl code of a preceding, matched pattern. โญ๏ธ
If a return is executed in the body of the match command, the scanfile command currently in progress returns, with the value passed to return as its return value. ๐
โ MATH COMMANDS ๐งฎ
Several extended math commands make many additional math functions available in TclX. On top of that, a whole set of procedures give you command access to the math functions supported by the expr command. Math girlies, this one's for you ๐
The following procedures provide command interfaces to the expr math functions. They take the same arguments as the expr functions and may take expressions as arguments. Slay ๐
abs acos asin atan2
atan ceil cos cosh
double exp floor fmod
hypot int log10 log
pow round sin sinh
sqrt tan tanh
max num1 ?..numN?expr max(num1, num2)
Returns the argument that has the highest numeric value. Each argument may be any integer or floating point value.
This functionality is also available as a math function max in the Tcl expr command. ๐
min num1 ?..numN?expr min(num1, num2)
Returns the argument that has the lowest numeric value. Each argument may be any integer or floating point value.
This functionality is also available as a math function min in the Tcl expr command. ๐ฅ
random limit|random seed ?seedval?โ generates a pseudorandom integer number greater than or equal to zero and less thanlimit. Ifseedis specified, then the command resets the random number generator to a starting point derived fromseedval. This allows one to reproduce pseudorandom number sequences for testing purposes โ reproducibility? obsessed ๐ฒ Ifseedvalis omitted, then the seed is set to a value based on current system state and the current time, providing a reasonably interesting and ever-changing seed. The main character of seeds, honestly ๐
๐ LIST MANIPULATION COMMANDS ๐
Extended Tcl came through with extra list-manipulation commands and procedures, bestie. Let's get into them ๐ฆ
intersect lista listbโ A procedure that hands you back the logical intersection of two lists. The list it returns? sorted, always. โจintersect3 lista listbโ The three-way split version, and omg it's giving main character energy. It intersects two lists and returns one list containing three lists inside it:- everything that was in
listabut not inlistb - the intersection of the two lists
- all the elements that were in
listbbut not inlista
- everything that was in
Every one of those returned lists is sorted. ๐
lassign list var ?var...?โ Assigns successive elements of a list to the variables you name. If you gave it more variable names than there are fields, the leftover variables get set to the empty string. If there's more elements than variables, you get back a list of the unassigned elements. no cap ๐ซถ
For example:
lassign {dave 100 200 {Dave Foo}} name uid gid longName
Assigns name to dave, uid to 100, gid to 200, and longName to Dave Foo. ๐
lcontain list elementโ Figure out if that element is a list element oflist. Contained? You get1. Not contained? You get0. periodt.lempty listโ Is this list empty? Empty =1, otherwise0. It's an alternative to comparing a list against an empty string โ except plot twist, it also checks for a string that's all whitespace, which counts as an empty list. ๐ธlmatch ?mode? list patternโ Searches the elements oflistand returns a list of everything matchingpattern. Nothing matched? You get an empty list back, it's fine, we move. ๐
The mode argument tells it how the list elements get matched against pattern, and it has to be one of these:
-exactโ the list element must contain exactly the same string aspattern.-globโpatternis a glob-style pattern matched against each list element using the same rules as thestring matchcommand.-regexpโpatternis treated as a regular expression and matched against each list element using the same rules as theregexpcommand.
Leave mode out and it defaults to -glob.
Heads up bestie: only the -exact comparison works on binary data. ๐ฉท
lrmdups listโ A procedure that removes duplicate elements from a list. And yes, the returned list is sorted. โจlvarcat var string ?string...?โ This one treats eachstringargument as a list, then concatenates them all onto the end of whatever's already insidevar, forming one single list. The list gets stored back intovarand returned as the result. Ifvardoesn't exist yet? Not a problem, it gets created. ๐lvarpop var ?indexExpr? ?string?โlvarpoppops (aka deletes) the element at the index given by the expressionindexExprfrom the list sitting inside the variablevar. Omit the index and0is assumed. Give it astringand the deleted element gets replaced by thatstringinstead. Either way, the replaced-or-deleted element is what gets returned. So like,lvarpop argv 0returns the first element ofargvand setsargvto contain the rest of the string. iconic behavior ๐
If the expression indexExpr starts with the string end, then end gets replaced with the index of the last element in the list. If the expression starts with len, then len gets replaced with the length of the list. ๐ฆ
lvarpush var string ?indexExpr?โlvarpushpushes (aka inserts)stringas an element into the list inside the variablevar. It inserts the element before positionindexExprin the list. Omit the index and0is assumed. Ifvardoesn't exist, it gets created. ๐ซถ
Same deal as above: if the expression indexExpr starts with the string end, then end gets replaced with the index of the last element in the list. If the expression starts with len, then len gets replaced with the length of the list.
Note that a value of end means insert the string before the last element. Don't be caught off guard bestie ๐
union lista listbโ A procedure that returns the logical union of the two lists you specified. Any duplicate elements get removed. bye dupes ๐
๐ KEYED LISTS ๐
Extended Tcl defines a special type of list called a keyed list, and honestly? It's a whole vibe. These lists give you a structured data type built on top of standard Tcl lists โ so like, structs in C, but make it Tcl. ๐
A keyed list is a list where each element holds a key and value pair. Those pairs are themselves stored as lists, with the key as the first element and the value as the second. These key-value pairs are called fields. Here's what a keyed list looks like:
{{NAME {Frank Zappa}} {JOB {musician and composer}}}
If the variable person held that list above, then keylget person NAME would return {Frank Zappa}. And running this command:
keylset person ID 106
would make person contain:
{{ID 106} {NAME {Frank Zappa}} {JOB {musician and composer}}
Fields can contain subfields, and . is the separator character. Subfields are just fields whose value is another keyed list. So this next list has the top level fields ID and NAME, plus the subfields NAME.FIRST and NAME.LAST:
{ID 106} {NAME {{FIRST Frank} {LAST Zappa}}}
And there is no limit to how deep those subfields can recurse, so you can build truly complex data structures with this. obsessed. ๐
Keyed lists get constructed and accessed through a bunch of commands. And important detail: all keyed list management commands take the name of the variable containing the keyed list as an argument (so basically passed by reference), rather than taking the list directly. iykyk ๐
keyldel listvar keyโ Deletes the field specified bykeyfrom the keyed list in the variablelistvar. This removes both the key and the value from the keyed list. both gone, no leftovers โจkeylget listvar ?key? ?retvar | {}?โ Returns the value associated withkeyfrom the keyed list in the variablelistvar. Ifretvarisn't specified, the value comes back as the result of the command. In that case, ifkeyisn't found in the list, an error results. ๐ญ
If retvar is specified and key is in the list, the value goes into the variable retvar and the command returns 1 โ meaning the key was present within the list. If key isn't in the list, the command returns 0 and retvar stays unchanged. And if you specify {} for retvar, the value is not returned at all โ which lets a Tcl programmer check whether a key is present in a keyed list without setting a variable as a side-effect. chef's kiss ๐ซถ
If key is omitted, then you get back a list of all the keys in the keyed list. ๐
keylkeys listvar ?key?โ Returns a list of the keys in the keyed list inside the variablelistvar. Ifkeyis specified, then it's the name of a key field whose subfield keys are to be retrieved. ๐ฆkeylset listvar key value ?key2 value2 ...?โ Sets the value associated withkey, in the keyed list contained in the variablelistvar, tovalue. Iflistvardoesn't exist, it gets created. Ifkeyisn't currently in the list, it gets added. If it already exists,valuereplaces the existing value. And you can specify multiple keywords and values if you want to. slay ๐
โจ STRING AND CHARACTER MANIPULATION COMMANDS โจ
okay bestie these are the glow-up commands for strings ๐ they let you classify characters, flip characters back and forth between character-y and number-y forms, index into a string, find out how long it is, grab a range of characters out of it, duplicate a string a bunch of times, and transliterate a string (basically the Unix tr program but make it fashion ๐
).
ccollate?-local? string1 string2 โ compares two strings, periodt. Returns-1if string1 is less than string2,0if they're equal, and1if string1 is greater than string2.
If -local is specified, the strings get compared according to the collation environment of the current locale ๐.
heads up bestie: this command does not work with binary or UTF data ๐ญ
cconcat?string1? ?string2? ?...? โ glues all the arguments together and hands you back the resulting string ๐ซถ. Normally the parser does string concatenation on its own, but every so often you just need a command that returns a string โ usually when a command is what's required to be evaluated. No separators get inserted between the strings, nope, not one โจ.
This command is UTF-aware ๐
cequalstring string โ compares two strings for equality. Returns1if string1 and string2 are identical and0if they're not. It's the shortcut forstring compareand it dodges all those problems where string expressions accidentally get treated as numbers ๐ (we've all been there).
This command is UTF-aware and it'll also work on binary data ๐ฅ
cindexstring indexExpr โ gives you back the character indexed by the expression indexExpr (zero based, obviously ๐ ) from string.
If the expression indexExpr starts with the string end, then end gets replaced with the index of the last character in the string. If the expression starts with len, then len gets replaced with the length of the string.
This command is UTF-aware โจ
clengthstring โ returns the length of string in characters. Literally just a shortcut for:
string length string
This command is UTF-aware ๐
crangestring firstExpr lastExpr โ returns a range of characters from string, starting at the character indexed by the expression firstExpr (zero-based) all the way until the character indexed by the expression lastExpr ๐.
If the expression firstExpr or lastExpr starts with the string end, then end gets replaced with the index of the last character in the string. If the expression starts with len, then len gets replaced with the length of the string.
This command is UTF-aware ๐ธ
csubstrstring firstExpr lengthExpr โ returns a range of characters from string, starting at the character indexed by the expression firstExpr (zero-based) and running for lengthExpr characters ๐ฆ.
If the expression firstExpr or lengthExpr starts with the string end, then end gets replaced with the index of the last character in the string. If the expression starts with len, then len gets replaced with the length of the string.
This command is UTF-aware โญ
ctokenstrvar separators โ parses a token out of a character string ๐ง. The string you're parsing lives in the variable named strvar. The string separators holds all the valid separator characters for tokens in the string. All the leading separators get skipped and the first token is what you get back. And the variable strvar gets modified to contain the remainder of the string that follows the token โ so watch out, it's mutating your variable ๐.
ngl this one does not work with binary data ๐ซ
ctype?-failindexvar? class string โctypefigures out whether all the characters in string belong to the specified class. It returns1if they're all of class, and0if they aren't, or if the string is empty (empty string = not it, sorry ๐). This command also serves as another way (besidesformatandscan) of converting between an ASCII character and its numeric value. Here are all thectypecommands you've got:ctype?-failindexvar?alnumstring โ tests that all characters are alphabetic or numeric characters, as defined by the character set ๐ค.ctype?-failindexvar?alphastring โ tests that all characters are alphabetic characters, as defined by the character set ๐ก.ctype?-failindexvar?asciistring โ tests that all characters are an ASCII character (a non-negative number less than0200) ๐ป.ctypecharnumber โ converts the numeric value, string, to an ASCII character. Number must be in the range0through the maximum Unicode values ๐.ctype?-failindexvar?cntrlstring โ tests that all characters are "control characters," as defined by the character set ๐ป.ctype?-failindexvar?digitstring โ tests that all characters are valid decimal digits, i.e.0through9๐ข.ctype?-failindexvar?graphstring โ tests that all characters are any character for whichctype printis true, except for space characters ๐ซง.ctype?-failindexvar?lowerstring โ tests that all characters are lowercase letters, as defined by the character set ๐ฝ.ctypeordcharacter โ converts a character into its decimal numeric value. The first character of the string gets converted to its numeric Unicode value ๐ขโจ.ctype?-failindexvar?spacestring โ tests that all characters are either a space, horizontal-tab, carriage return, newline, vertical-tab, or form-feed ๐ฌ๏ธ.ctype?-failindexvar?printstring โ tests that all characters are a space, or any character for whichctype alnumorctype punctis true, or any other "printing character" as defined by the character set ๐จ๏ธ.ctype?-failindexvar?punctstring โ tests that all characters are made up of any of the characters other than the ones for whichalnum,cntrl, orspaceis true โ๏ธ.ctype?-failindexvar?upperstring โ tests that all characters are uppercase letters, as defined by the character set ๐ผ.ctype?-failindexvar?xdigitstring โ tests that all characters are valid hexadecimal digits, that is0through9,athroughf, orAthroughF๐งฎ.
If -failindex is specified, then the index into string of the first character that did not match the class gets returned in var ๐.
replicatestring countExpr โ gives you string, replicated the number of times indicated by the expression countExpr ๐. So yes, it's the copy-paste button but make it a command.
This command is UTF-aware and it'll work with binary data ๐
translitinrange outrange string โ translates the characters in string, swapping characters that show up in inrange for the corresponding character in outrange ๐. Inrange and outrange can be a list of characters, or a range in the formA-M. For example:
translit a-z A-Z foobar
bestie listen: this command currently only supports characters in the ASCII range โ UTF-8 characters outside of this range will generate an error ๐ญ๐ซ
๐ XPG/3 MESSAGE CATALOG COMMANDS ๐ฌ
These commands give you a Tcl interface to message catalogs that are compliant with the X/Open Portability Guide, Version 3 (aka XPG/3). Periodt.
So here's the vibe: Tcl programmers can use message catalogs to build applications that are language-independent. With message catalogs, your prompts, your messages, your menus, literally all of it can exist in however many languages you want, and you can tweak them and add brand-new languages without touching a single line of Tcl or C source code. That's the whole point โ it majorly eases the maintenance pain of supporting multiple languages. ๐
A default text message gets passed to the command that fetches entries from the catalogs. This is the iconic move where the Tcl programmer can make catalogs full of messages in all the languages, but still have a set of default messages ready no matter what, so the program just keeps on slaying even when there are no catalogs present at all. โจ
So the normal approach? Ignore errors on catopen, and then catgets will just hand you the default message that was specified in the call. Simple as that.
The Tcl message catalog commands normally ignore most errors. But if you actually want to detect errors, there's a special option for that. It's normally only used during debugging, to make sure catalogs are actually being used. And if your Unix implementation doesn't have XPG/3 message catalog support at all? Stubs get compiled in that create a version of catgets that always returns the default string. Which means porting software to environments without message catalog support is easy-peasy. ๐ฆ
Heads up bestie: message catalogs are global to the process, so an application with multiple Tcl interpreters inside the same process may pass and share message catalog handles. No cap.
๐ The commands
catopen ?-fail | -nofail? catnameโ Opens the message catalog catname. This can be a relative path name, and if it is, theNLSPATHenvironment variable gets searched to find an absolute path to the catalog. You get back a handle shaped likemsgcatN. Normally errors are ignored, and ifcatopenfails, you still get a handle โ but to an unopened message catalog. (That handle can still be passed tocatgetsandcatclose, and it makescatgetsjust return the default string, like we said up top.) If you specify-fail, then an error is returned when the open fails. The-nofailoption specifies the default behavior of not returning an error whencatopenfails to open the specified catalog. And if the handle from a failedcatopenis passed tocatgets, the default string is what you get. ๐คทโ๏ธcatgets catHandle setnum msgnum defaultstrโ Retrieves a message from a message catalog. CatHandle should be a Tcl message catalog handle thatcatopenreturned. Setnum is the message set number, and msgnum is the message number. If the catalog was never opened, or the message set or message number can't be found, then you get the default string, defaultstr, returned. ๐catclose ?-fail | -nofail? cathandleโ Closes the message catalog specified by cathandle. Normally errors are ignored. If-failis specified, any errors from closing the catalog file get returned. The-nofailoption specifies the default behavior of not returning an error. Lowkey important: using-failonly makes sense if you also specified it in the call tocatopen. ๐mainloopโ This procedure sets up a top-level event loop. Events are processed until there are no more active event sources, at which point the process exits. It's used to build event-oriented programs using the TclX shell, in a style similar to the one you'd use withwish. If the global variabletcl_interactiveexists and has a true value, an interactive command handler gets started as well. And if that command handler gets terminated by an EOF, the process will be exited. ๐ฅ
๐ HELP FACILITY ๐
The help facility lets you look up help pages that were extracted from the standard Tcl manual pages and Tcl scripts during Tcl installation. Help files are structured as a multilevel tree of subjects and help pages. They're found by searching directories named help in the directories listed in the auto_path variable. All the files in that list of help directories form a virtual root of the help tree โ which is the whole genius of it, because it means multiple applications can provide help trees without having their files live in the same directory. ๐ง
You can access the help facility two ways: as interactive commands in the Extended Tcl shell, or as an interactive Tk-based program (if you built Extended Tcl with Tk, that is).
To run the Tk-based interactive help program:
tclhelp ?addpaths?
Where addpaths are additional paths to search for help directories. By default, only the auto_path used by tclhelp is searched. That gets you help on Tcl, Extended Tcl and Tk. โจ
The following interactive Tcl commands and options come with the help package:
helpโ Help with no arguments lists all the help subjects and pages under the current help subject. ๐help subjectโ Displays all the help pages and lower-level subjects (if any exist) under the subject subject.help subject/helppageโ Displays the specified help page. The help output gets passed through a simple pager if it goes over 23 lines, pausing and waiting for a return to be entered. If you enter any other character, the output is terminated. ๐helpcd ?subject?โ Changes the current subject, which is a lot like the Unix current directory. If subject isn't specified, you go back to the top level of the help tree. Help subject path names may also include..elements. ๐ธhelppwdโ Displays the current help subject.help help | ?โ Displays help on the help facility, at any directory level. Very meta of her. ๐apropos patternโ This command locates subjects by searching their one-line descriptions for a pattern. Apropos is the move when you remember part of the name or description of a command and want to search through the one-line summaries for matching lines. Full regular expressions may be specified (see theregexpcommand). ๐
๐ฆ TCL LOADABLE LIBRARIES AND PACKAGES ๐
Extended Tcl supports standard Tcl tclIndex libraries and package libraries. A single package library file can contain multiple independent Tcl packages. And a package is a named collection of related Tcl procedures plus initialization code. โจ
The package library file is just a regular Unix text file โ editable with your favorite text editor, obviously โ containing packages of Tcl source code. Its name must have the suffix .tlib. An index file with the same prefix name and the suffix .tndx lives in the same directory as the .tlib file. And the .tndx gets automatically created whenever it's out of date or missing (provided there's write access to the directory). ๐ฆ
The variable auto_path contains a list of directories that get searched for libraries. The first time an unknown command trap is taken, the indexes for the libraries are loaded into memory. If auto_path gets changed while a program is running, it will be re-searched. Only the first package of a given name found during the execution of a program is loaded. You can override that with the loadlibindex command. ๐
The start of a package is delimited by:
#@package: package_name proc1 ?..procN?
These lines must start in column one. Everything between the #@package: keyword and the next #@package: keyword, or a #@packend keyword, or the end of the file, becomes part of the named package. The specified procedures, proc1..procN, are the entry points of the package. When a command named in a package specification gets executed and detected as an unknown command, all the code in the specified package will be sourced. That package should define all the procedures named on the package line, define any support procedures the package requires, and do any package-specific initialization. Package declarations can be continued on subsequent lines using standard Tcl backslash line continuations. And the #@packend keyword is useful for making sure only the minimum required section of code gets sourced โ so, for example, a big chonky comment block at the beginning of the next file won't get loaded. ๐
Care should be taken when defining package_name, because the first package found in the path with a given name is the one that gets loaded. Which is actually useful when you're developing a new version of packages installed on the system. ๐
For example, in a package source file, the presence of this line:
#@package: directory_stack pushd popd dirs
says that the text lines following that line in the package file, up to the next package line or the end of the file, are a package named directory_stack, and that an attempt to execute pushd, popd or dirs when the routine isn't already defined will cause the directory_stack portion of the package file to be loaded. ๐
๐ PACKAGE LIBRARY MANAGEMENT COMMANDS ๐
okay so bestie, this is the part where TclX lets you build your own lil package libraries, and honestly? it's giving little free library in the front yard but for code ๐โจ
There are a bunch of commands for building and managing package libraries. The ones listed here are the ones that are extended versions of the standard Tcl library commands โ and also, no cap, all the standard Tcl library management commands and variables are supported too, so nothing you already love goes away ๐
โจ the commands โจ
auto_commands?-loaders? โ lists the names of every known loadable procedure and command procedure ๐ And if you pass-loaders, it also hands you back the command that will be executed to load that command. like a little sneak peek at the machinery, iykyk.buildpackageindexlibfilelist โ builds index files for package libraries. The libfilelist argument is a list of package libraries, and every single name has to end with the suffix.tlib(periodt, no exceptions ๐ ). A corresponding.tndxfile gets built for each one. Also important: the user must have write access to the directory containing each library, otherwise this is not happening bestie.convert_libtclIndex packagelib ?ignore? โ converts an Ousterhout styletclIndexindex file, plus the source files it points to, into a package library called packagelib. If packagelib doesn't already have a.tlibextension, one gets added for you, so don't stress ๐ซถ Any files specified intclIndexthat are in the ignore list get skipped. And heads up: files listed in ignore should just be the base file names, not full paths โ don't be out here typing whole directory trees, she's not gonna match them.loadlibindexlibfile.tlib โ loads the package library index of the library file libfile (which must have the.tlibsuffix). Package library indexes along theauto_pathget loaded automatically on the firstdemand_load, so this command exists for when you need to explicitly load libraries that aren't in the path at all. If the index file (with a.tndxsuffix) doesn't exist or is out of date, it'll be rebuilt โ but only if the user has directory permissions to create it. And here's the dramatic part ๐ญ if a package with the same name as a package in libfile.tlib has already been loaded, its definition gets overridden by the new package. BUT โ and this is a big but โ if any procedure has actually been used from the previously defined package, then the procedures from libfile.tlib won't be loaded at all. no takebacks, the vibe check has already happened ๐auto_packages?-location? โ returns a list of the names of all defined packages. If you throw-locationin there, you get a list of pairs, where each pair is the package name plus the.tlibpath name, offset, and length of the package inside that library. very detective energy ๐auto_load_filefile โ sources a file, exactly as thesourcecommand does, except it goes searching throughauto_pathfor the file instead of making you spell out the whole location. it's the find-my-friend of file loading ๐ฆsearchpathpath file โ searches all the directories in the specified path (which is a Tcl list) for the specified file. Returns the full path name of the file if she finds it, or an empty string if the requested file could not be found. rude, but honest ๐ธ
๐ okay that's the whole dang page ๐
and that's a wrap on the whole thing bestie, we made it to the end ๐ lowkey emotional. this page is TclX(3tcl) โ version 3, from good ol' Tcl โ and it's stamped with a date down at the bottom in the footer next to that version, so if you ever need to cite your sources, that's where the receipts live ๐โจ now go forth and slay those package libraries fr fr ๐
๐ซถ
๐ฆ where this page comes from
- ubuntu stonking: tcl-tclx-doc 8.6.3+dfsg-3 ยท NTP
- Copyright 1992-1999 Karl Lehenbauer and Mark Diekhans
- Copyright 2004 ActiveState Corporation
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms