TclX(TCL)
๐ฆ TclX(TCL) โ Extended Tcl: Extended command set for Tcl โจ
๐ NAME
TclX โ Extended Tcl: Extended command set for Tcl.
๐ป SYNOPSIS
package require Tclx
โจ INTRODUCTION
Okay bestie, this man page is the whole glow-up guide for every extension that Extended Tcl (TclX) adds to Tcl ๐. TclX extends Tclโs capabilities by adding new commands to it, without changing the syntax of standard Tcl. Extended Tcl is a superset of standard Tcl and is built alongside the standard Tcl sources.
Extended Tcl was created by Karl Lehenbauer and Mark Diekhans and is freely redistributable for any use without license or fee. Iconic behavior, honestly ๐.
Available since 1989, Extended Tcl, also known as TclX, not only adds capabilities to Tcl, but 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. Itโs giving โmain character energyโ in the Tcl ecosystem fr fr ๐.
Extended Tcl introduces a set of new commands and a user-extensible library of useful Tcl procedures, any of which can be automatically loaded on the first attempt to execute it.
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 begin an interactive session with Tcl, a facility for tracing execution, and a looping command.
๐ dirs
This procedure lists the directories in the directory stack.
๐ฌ commandloop
commandloop ?-async? ?-interactive on | off | tty? ?-prompt1 cmd? ?-prompt2 cmd? ?-endcommand cmd?
Create an interactive command loop reading commands from stdin and writing results to stdout. Command loops can be blocking or event oriented. This command is useful for Tcl scripts that do not normally converse interactively with a user through a Tcl command interpreter, but which sometimes want to enter this mode, perhaps for debugging or 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 may be 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 evaluated and its result is used for the main command prompt. If not specified, the command intcl_prompt1is evaluated to output the prompt. Note the difference in behavior:cmdresults are used, whiletcl_prompt1outputs. This is to allow for future expansion to command loops that write to other thanstdout.-prompt2 cmdโ If specified,cmdis evaluated and its result is 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 typed without aborting the program in progress.
๐ง coalesce
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. If none of the variables exist and the default value wasnโt specified using -default, returns the empty string.
๐ฃ๏ธ echo
echo ?str ...?
Writes zero or more strings to standard output, followed by a newline.
๐ infox
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 may be used.have_msgcatsโ Return1if XPG message catalogs are available,0if they are not.catgetsis 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
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.
๐ณ for_recursive_glob
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
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.
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.
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.
popdโ pops the top directory entry off the directory stack and makes it the current directory. bye-bye old dir, hello new one ๐pushd ?dir?โ pushes the current directory onto the directory stack, thencds to the directory you named. If you donโt name a directory, the current one gets pushed but nothing changes. lowkey a little โcopy my vibeโ move ๐ซถrecursive_glob dirlist globlistโ returns a list of recursively matched files. Every directory indirlistgets searched recursively, breadth-first, and each file it finds gets checked against the file glob patterns ingloblist. Symbolic links are not followed โ no chasing rabbit holes ๐๐ซshowproc ?procname ...?โ lists the definition of the named procedures, loading them first if they arenโt already loaded. If you pass no procedure names, it returns the definitions of all currently loaded procedures. itโs giving โshow me the receiptsโ ๐โจtry_eval code catch ?finally?โ evaluatescodein the current context.
If an error happens during that evaluation and catch is not empty, then catch gets evaluated to handle the error. The result of the command, containing the error message, is stored in a global variable errorResult. The global variables errorResult, errorInfo and errorCode are imported into the current scope โ no need to run a global command. The result of the catch command becomes the result of the try_eval command.
If you want to continue the error that caused catch to be evaluated, use this exact move:
error $errorResult $errorCode $errorInfo
If the finally argument is supplied and not empty, itโs evaluated after both the code and catch commands. If an error happens during finally, that becomes the result of try_eval. Otherwise the result of either code or catch is preserved, as described above. final girl energy, but make it cleanup ๐
๐ DEBUGGING AND DEVELOPMENT COMMANDS ๐
This section is all about commands and procedures that are useful for developing and debugging Tcl scripts. ngl this is where the detective work happens ๐๐
cmdtrace level | on ?noeval? ?notruncate? ?procs? ?fileid? ?command cmd?โ prints a trace statement for all commands executed at depthlevelor below (1is the top level). Ifonis specified, all commands at any level are traced. The following options are available:noevalโ causes arguments to be printed unevaluated. Ifnoevalis specified, the arguments are printed before evaluation. Otherwise, theyโre printed afterwards.
If the command line is longer than 60 characters, itโs truncated to 60 and a ... is postpended to show there was more output than was displayed. If an evaluated argument contains a space, the entire argument gets enclosed inside braces ({}) so the reader can visually separate arguments from each other.
notruncateโ disables the truncation of commands and evaluated arguments. no more cutting off the fit, bestie โ๏ธ๐ซprocsโ enables 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) are not traced ifprocsis specified. This is especially useful for greatly reducingcmdtraceoutput while debugging. less noise, more clue ๐ต๏ธโโ๏ธfileidโ this is a file id as returned by theopencommand. If specified, trace output is written to the file instead ofstdout. A stdio buffer flush is done after every line is written so the trace can be monitored externally or provide useful info for debugging problems that cause core dumps. ๐โก๏ธ๐command cmdโ calls the specified commandcmdwhen each command is executed 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 enable tracing to a file during development. If a failure occurs, a trace is then available when needed. Command tracing slows down execution of code, so it should be removed when the code is debugged. The following command enables tracing to a file for the remainder of the program:
cmdtrace on [open cmd.log w]
The command option causes a user-specified trace command to be called for each command executed. That command gets the following arguments appended before evaluation:
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.
The command should be built so it still works if additional arguments are added in the future. Itโs suggested that the command be a proc with the final argument being args. future-proof that icon ๐ฎ
Tracing is turned off while the command is being executed. The values of the errorInfo and errorCode variables are saved and restored on return from the command. Itโs the commandโs responsibility to preserve all other state.
If an error happens during execution of command, an error message is dumped to stderr and tracing is disabled. The underlying mechanism this functionality is built on does not support returning an error to the interpreter. thatโs the lore, bestie ๐ญ
cmdtrace offโ turns off all tracing. bye trace era ๐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 donโt name any, to a temporary file. Then it calls an editor on it (as specified by theEDITORenvironment variable, orviif none is specified), then sources the file back in if it was changed. editor-core ๐ปโจprofile ?-commands? ?-eval? onprofile off arrayVar
This command collects a performance profile of a Tcl script. It collects data at the Tcl procedure level: the number of calls to a procedure, and the amount of real and CPU time. Time is also collected for the global context. The procedure data is collected by bucketing it based on the procedure call stack, which lets you determine 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 this data may still be useful for analysis.
The off option turns off profiling and moves the collected data to 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 used when reporting where time is spent. So upleveled code is reported in the context it was executed in, not the context where uplevel was called. If the -eval option is specified, the procedure evaluation (call) stack is used instead of the procedure scope stack. Upleveled code is reported in the context of the procedure that did the uplevel.
A Tcl procedure profrep is supplied for reducing the data and producing a report. data girl summer ๐๐
On Windows, the profile command only reports elapsed real time. CPU time is not available and is reported as zero.
profrep profDataVar sortKey ?outFile? ?userTitle?โ generates a report from data collected by theprofilecommand.profDataVaris the name of the array containing the data returned byprofile.sortKeysays which data value to sort by, and should be one ofcalls,cpuorreal.outFileis the name of the file to write the report to; if omitted,stdoutis assumed.userTitleis an optional title line added 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, 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 it was executed in, not the context where the uplevel was called. stack trace but make it fashion ๐
saveprocs fileName ?proc...?โ saves the definition of the named procedure, or all currently defined procedures if none is specified, tofileName. save file, slay file ๐พโจ
๐ธ UNIX ACCESS COMMANDS ๐ธ
These commands give you access to lots of basic Unix facilities, including process handling, date and time processing, signal handling and executing commands via the shell. we love a Unix field trip ๐ง๐
alarm secondsโ tells the system to send aSIGALRMsignal in the specified number of seconds. This is a floating point number, so fractions of a second may be specified. Ifsecondsis0.0, any previous alarm request is canceled. Only one alarm at a time may be active; the command returns the number of seconds left in the previous alarm. On systems without thesetitimersystem call,secondsis rounded up to an integer number of seconds. โฐ๐ฅ
The alarm command is not available on Windows. windows bestie, this one isnโt for you ๐ญ๐ซถ
๐งต execl โ swap your whole self out for another program
execl ?-argv0 argv0? prog ?arglist?
Okay so this one literally does an execl โ it replaces the current program (either Extended Tcl, or some app that has Extended Tcl embedded in it โจ) with prog, and hands prog the args sitting in the list arglist.
-argv0argv0 โ tells it that argv0 should get passed to the program asargv [0]instead ofprog. Cute little name-swap moment ๐
โ ๏ธ Bestie, listen: if you useexeclinside a Tk application and it fails, you cannot do anything that touches the X server โ otherwise the X server hits you with aBadWindowerror. That includes running the Tk version of theexitcommand, no cap. The suggested way to abort Tk apps after a failedexeclis this:
kill [id process]
On Windows, where fork isn't available, execl starts a new process and returns the process id. ๐ช
๐ณ chroot โ new root, who dis
chroot dirname
Changes the root directory to dirname by invoking the POSIX chroot(2) system call. This only works if you're running as root โ sorry not sorry, that's just the vibe check the kernel enforces ๐
๐ด fork โ clone yourself, it's giving mitosis
fork
Forks the current Tcl process. fork returns zero to the child process, and the process number of the child to the parent process. If the fork fails, a Tcl error gets generated. ๐
๐จ Flush first, seriously: if you're not gonna do anexeclbefore the child process does output, or if you're gonna do a close-and-dup sequence onstdoutorstderr, then flushstdout,stderr, and any other open output file before the fork. Otherwise the characters from the parent process still chilling in the buffers get output by both the parent and the child. Double-printed chaos, we don't want that ๐
Also โ if you're forking in a Tk-based application, you must execl before doing any window operations in the child, or the X server will hit you with a BadWindow error.
fork is not available on Windows.
๐ชช id โ who even am I
id options
This command is your whole little toolkit for getting, setting and converting user, group and process ids. The id command has these options:
id user ?name?โ user stuff, see belowid userid ?uid?โ sets the real and effective user ID tonameoruid, if the 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 uidโ convert a user ID number to a user name ๐ซถid convert user nameโ convert a user name to a user ID number, the other direction ๐id group ?name?โ group stuff, see belowid groupid ?gid?โ sets the real and effective group ID tonameorgid, if the name (or gid) is valid and permissions allow it. If the group name (or gid) isn't specified, the current group name (or gid) is returnedid groupsโ return the current group access list of the process, as group namesid groupidsโ return the current group access list of the process, as id numbersid convert groupid gidโ convert a group ID number to a group nameid convert group nameโ convert a group name to a group ID numberid effective userโ return the effective user name ๐id effective useridโ return the effective user ID numberid effective groupโ return the effective group nameid effective groupidโ return the effective group ID numberid 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 onid processโ return the process ID of the current processid process parentโ return the process ID of the parent of the current processid process groupโ return the process group ID of the current processid process group setโ set the process group ID of the current process to its process IDid hostโ returns the standard host name of the machine the process is executing on (yep, it's listed twice in the original, she contains multitudes ๐)
On Windows, only the host and process options are implemented.
๐ kill โ tell a process to go away
kill ?-pgroup ?signal? idlist
Sends a signal to each process in the list idlist, if permitted. signal, if present, is the signal number or the symbolic name of the signal โ see the signal system call manual page. The leading SIG is optional when you specify the signal by its symbolic name. The default for signo is 15, SIGTERM. ๐ฅ
-pgroupโ 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, kill is capable of terminating a process, but not of sending an arbitrary signal.
๐ link โ make a whole new directory entry
link ?-sym? srcpath destpath
Creates a directory entry, destpath, linking it to the existing file, srcpath. If -sym is specified, a symbolic link is created rather than a hard link. (The -sym option is only available on systems that support symbolic links. ๐ง)
link is not available on Windows. Use the Tcl 8.4+ file link command instead โ glow up ๐
๐ nice โ be a little kinder to the CPU
nice ?priorityincr?
Changes or returns the process priority. If priorityincr is omitted, the current priority is returned. If priorityincr is positive, it gets added to the current priority level, up to a system defined maximum (normally 19).
Negative priorityincr values cumulatively increase the program's priority down to a system defined minimum (normally -19) โ but increasing priority with negative niceness values will only work for the superuser ๐ no shortcuts, bestie.
The new priority is returned.
nice is not available on Windows.
๐ readdir โ what's in this folder, fr fr
readdir ?-hidden? dirPath
Returns a list containing the contents of the directory dirPath. The directory entries "." and ".." are not returned, so no boring dot noise โจ
-hiddenโ on Windows, this may be specified to include hidden files in the result. This flag is ignored on Unix systems. ๐
๐ก signal โ the whole signals situation
signal ?-restart? action siglist ?command?
๐จ Warning, and this one's important: if signals are being used as an event source (atrapaction), rather than generating an error to terminate a task, you must use the-restartoption. That causes a blocked system call โ likereadorwaitpidโ to be restarted rather than generate an error. Failing to do this may result in unexpected errors when a signal arrives while you're inside one of those system calls. When available,-restartcan prevent this problem. ๐
If -restart is 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. The -restart option is not available on all operating systems, and using it will generate an error when it isn't supported. Use infox have_signal_restart to check for availability ๐ต๏ธโโ๏ธ
So this command specifies what 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 signals (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, since they can not be modified, periodt. ๐
defaultโ perform the system default action when the signal is received (see thesignalsystem call documentation)ignoreโ ignore the signal. Nothing to see here ๐errorโ generate a catchable Tcl error. It'll 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, so you can write portable code ๐ซถ
trapโ when the signal occurs, executecommandand continue execution ifcommanddoesn't return an error. The command is executed in the global context. The command gets edited before execution, replacing occurrences of%Swith the signal name, and occurrences of%%result in a single%. This editing happens 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 is 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 block) and a1if it is blocked, and a flag indicating if restarting of system calls is specified. The actions may be 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 thegetaction. 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 those systems, SIGCHLD is not 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's meant to be portable between both types of systems, use this approach ๐งโจ
Signals are not processed until after the Tcl command that's running when the signal arrives finishes up. Like, it waits its turn, no cutting in line ๐
. If an interactive Tcl shell is running, then SIGINT gets set to error; non-interactive Tcl sessions leave SIGINT unchanged from when the process started (which is normally the default for foreground processes, and ignore for processes chillin' in the background).
sleepseconds โ Sleeps the Extended Tcl process for seconds seconds. And lowkey important: if seconds is given as a decimal number, it gets truncated to an integer value. So no,sleep 2.9is not giving you 2.9 seconds of nap time ๐.systemcmdstr1 ?cmdstr2...? โ Concatenatescmdstr1,cmdstr2etc. with space separators (see theconcatcommand) into one single command, then evaluates it using the standard system shell. On Unix systems that's/bin/sh, and on Windows it'scommand.com. It returns the exit code of the command.
Fr fr, this is how it differs from exec: system does not return the executed command's standard output as the result string, and system goes through the Unix shell so you get wildcard expansion, redirection, etc., exactly like you'd expect from an sh command line. Iconic shell behaviour, no cap โจ
sync?fileId? โ If fileId isn't specified, or if it is specified and this system doesn't 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 that Tcl fileId, forcing all pending output to that file out to disk ๐ซถ
If fileId is specified, the file must be writable. A flush gets issued against the fileId before the sync.
Use the infox have_fsync command to figure out whether sync fileId is gonna do a sync or a fsync. Vibes only, bestie.
timesโ Returns a list containing the process and child execution times, shaped like:
utime stime cutime cstime
Also peep the times(2) system call manual page. The values are in milliseconds โฑ๏ธ
umask?octalmask? โ Sets the file-creation mode mask to the octal value of octalmask. If octalmask is omitted, the current mask is returned. Simple as ๐wait?-nohang? ?-untraced? ?-pgroup? ?pid? โ Waits for a process created with theexeclcommand to terminate, either from an untrapped signal or from a call to theexitsystem call. If the process id pid is specified, it waits on that process; otherwise it waits on any child process to terminate.
If -nohang is specified, then don't block waiting on a process to terminate โ and if no process is immediately available, it returns an empty list. If -untraced is specified, then the status of child processes that are stopped (and whose status hasn't been reported yet since they stopped) are also returned. If -pgroup is specified and pid is not specified, then it waits on any child process whose process group ID is the same as the calling process. If pid is specified along with -pgroup, then pid is taken as a process group ID, and it waits on any process in that process group to terminate ๐ง
wait returns a list containing three elements. First element: 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 ๐
Heads up bestie: it is possible to wait on processes that were created in the background with theexeccommand. BUT โ if any otherexeccommand runs after the process terminates, then that process status gets reaped by theexeccommand and will not be available to thewaitcommand ๐ญ gone, reduced to atoms.
On systems without the waitpid system call, the -nohang, -untraced and -pgroup options are not available. The infox have_waitpid command may be used to determine whether this functionality exists on your system.
๐ธ FILE COMMANDS ๐ธ
These commands give you extended file access and manipulation โ it's giving main character energy for your filesystem ๐. That includes searching ASCII-sorted data files, copying files, duplicating file descriptors, controlling file access options, retrieving open file status, and creating pipes with the pipe system call. Also linking files, setting file/process/user attributes, and truncating files. And there's an interface to the select system call available on Unix systems that support it โจ
Real talk: Tcl file I/O is implemented on top of thestdiolibrary, so by default the file is buffered. When you're communicating to a process through a pipe, aflushcommand should be issued to force the data out ๐ซถ Alternatively, thefcntlcommand may be used to set the buffering mode of a file to line-buffered or unbuffered. iykyk.
bsearchfileId key ?retvar? ?compare_proc? โ Searches 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, and that 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 โ otherwise erroneous results will occur. Periodt. No shortcuts.
Also: this command does not work on files containing binary data (bytes of zero). Just so you know ๐
channelfdchannel โ Gets the unix file descriptor (an integer) for channel using theTcl_GetChannelHandleAPI. On any error the return value is-1.
The channelfd command is not available on Windows ๐
chmod[-fileid] mode filelist โ Sets 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. To specify a mode as octal, prefix it with a"0"(e.g.0622) ๐
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 check if you've got it.
The chmod command is not available on Windows.
chown[-fileid] owner | {owner group} filelist โ Sets the 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 โ Sets 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.
dupfileId ?targetFileId? โ Duplicates an open file. A new file id is opened that addresses the same file as fileId ๐ฏ
If targetFileId is specified, then the file is dup'd 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 it 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. Super 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 may be specified for targetFileId. The dup command does not work on sockets on Windows ๐ญ
fcntlfileId 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 may only be gotten, not modified. The following attributes may be specified:
โจ the attributes, bestie โจ
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 a 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โ The file is not buffered. If set, then there's no buffering for the file. Zero buffer, zero vibes ๐LINEBUFโ the output file gets line buffered โจ the buffer flushes when a newline gets written, when the buffer is full, or when input is requested. That's it, that's the whole vibe.KEEPALIVEโ keeps a socket connection alive ๐ซถ here's the tea: ifSIGPIPEis enabled, then it gets sent when the connection breaks and data gets written to the socket. IfSIGPIPEis ignored, an error is returned on the write instead. This attribute is valid only on sockets. And by default,SIGPIPEis ignored in Tcl.
So real talk: NONBLOCK, NOBUF and LINEBUF are all here for compatibility with older scripts ๐ the fconfigure command is the preferred method of getting and setting these attributes. Use that one, bestie.
โ ๏ธ Heads up: theAPPENDandCLOEXECoptions are not available on Windows.
๐ flock options fileId ?start? ?length? ?origin?
Okay so this one places a lock on all of a file or part of it ๐
the lock is either advisory or mandatory, depending on the mode bits of the file. It's 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", 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", it's relative to the end-of-file (negative is before the EOF, positive is after it). And if origin is omitted, start is assumed.
The following options are recognized, bestie:
-readโ place a read lock on the file ๐ multiple processes may be accessing the file with read-locks. Sharing is caring.-writeโ place a write lock on the file โ๏ธ only one process may be accessing a file if there is a write lock. Sorry, main character energy only.-nowaitโ if specified, then the process will not block if the lock can't be obtained ๐โโ๏ธ with this option, the command returns1if the lock is obtained and0if it is not.
See your system's fcntl system call documentation for the full details of how file locking behaves, fr fr. And if locking is being done on ranges of a file, it's best to use unbuffered file access (see the fcntl command).
๐จ The flock command is not available on Windows 95. It is available on Windows NT.
๐ for_file var filename code
This procedure implements a loop over the contents of a file, and honestly? iconic ๐ 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.
For example, the command
for_file line /etc/passwd {echo $line}
would echo all the lines in the password file ๐
๐ 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 the flock command, so just go read that one for more details.
๐จ The funlock command is not available on Windows 95. It is available on Windows NT.
๐ fstat fileId ?item? | ?stat arrayvar?
Obtains 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 changedevโ 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 groupinoโ 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 modifiednlinkโ the number of links to the filesizeโ the file size in bytes ๐ttyโ if the file is associated with a terminal, then1, otherwise0typeโ the type of the file in symbolic form, which is one of the following values:file,directory,characterSpecial,blockSpecial,fifo,link, orsocketuidโ 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 come back with the array or keyed list forms, so don't @ me:
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 [-fileid] file newsize
Truncates a file to have a length of at most newsize bytes ๐
If the option -fileid is specified, 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 is not available. The commandinfox have_truncatewill indicate if this command may truncate by file path. The commandinfox have_ftruncatewill indicate if this command may truncate by file id.
๐จ The -fileid option is not available on Windows.
๐ lgets fileId ?varName?
Reads the next Tcl list from the file given by fileId and discards the terminating newline character โจ this command differs from the gets command in that it reads Tcl lists rather than lines. If the list contains newlines or binary data, then that newline or bytes of zero will be returned as part of the result. Only a newline not quoted as part of the list indicates the end of the list. There's no corresponding command for outputting lists, because puts will do this 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 ๐ญ
If varName is not specified, then the return value will be the line (minus the newline character), or an empty string if the end of the file is reached before reading any characters. An empty string will also be returned if a line contains no characters except the newline, so eof may have to be used to determine what really happened ๐
The lgets command may be used to read and write lists containing binary data, however translation must be set to lf or the data may be corrupted ๐ซ
lgets is currently supported on non-blocking files.
๐งช pipe ?fileId_var_r fileId_var_w?
Creates 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 ๐
๐ 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.
๐ select readfileIds ?writefileIds? ?exceptfileIds? ?timeout?
This command lets an Extended Tcl program wait on zero or more files being ready for reading, ready for writing, having an exceptional condition pending, or waiting for a timeout period to expire โจ readFileIds, writeFileIds and exceptFileIds are each lists of fileIds, as returned from open, to query. An empty list ({}) may be specified if a category isn't 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.
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 โ 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
{file3 file4} {file6} {}
or perhaps
file3 {} {}
Quick heads-up for the Windows girlies: on Windows, only sockets can be used with theselectcommand. Pipes, like the ones you get back from theopencommand, are not supported. No pipe dreams, sorry ๐
write_file fileName string ?string...?โ this procedure writes the specified strings to the named file. That's it, that's the whole vibe: you point at a file, you hand it strings, it writes them. โจ
๐ NETWORK PROGRAMMING SUPPORT ๐
TclX is out here complementing the Tcl socket command, bestie โ it's giving supportive friend energy. ๐
The host_info command is your go-to for getting info about a host by name or IP address. And that's not all โ the fstat and fcntl commands also give you options for querying and controlling connected sockets. Oh, and if you wanna grab the host name of the local system? Use the id host command. ๐ซถ
host_info option host
Obtain information about an Internet host. The argument host can be either a host name or an IP address. ๐
The following subcommands are recognized:
addressesโ returns the list of IP addresses for host. ๐official_nameโ returns the official name for host. ๐aliasesโ returns the list of aliases for host. Just so you know (and this is the important little detail, don't skip it): these are IP number aliases, not DNS CNAME aliases. Seeifconfig(2). ๐ง
๐ FILE SCANNING COMMANDS ๐
Okay so this is the part where TclX lowkey becomes awk but make itโจdeclarativeโจ.
These commands give you a facility to scan files, matching lines of the file against regular expressions and executing Tcl code on a match. With this facility you can use Tcl to do the sort of file processing that is traditionally done with awk. And honestly? Since Tcl's approach is more declarative, some of the scripts that can be rather difficult to write in awk are simple to code in Tcl. Ate. ๐ฅ
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 the expressions are matched. iykyk ๐ธ
scancontext ?option?
This command 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 do not 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โ create a new scan context. Thescanmatchcommand is used to define patterns in the context. A contexthandle is 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โ delete the scan context identified by contexthandle, and free all of the match statements and compiled regular expressions associated with the specified context. Cleanup slay. ๐งนscancontext copyfile contexthandle ?filehandle?โ set or return the file handle that unmatched lines are copied to (seescanfile). If filehandle is 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 filehandle is{}, then it removes any copy file specification for the context. ๐
scanfile ?-copyfile copyFileId? contexthandle fileId
Scan the file specified by fileId, starting from the current file position. Check all patterns in the scan context specified by contexthandle against it, executing the match commands corresponding to patterns 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 using the scancontext copyfile command, the file is disassociated from the scan context at the end of the scan. ๐
โ ๏ธ Real talk: this command does not work on files containing binary data (bytes of zero). Don't come for it, it's just not built for that. ๐
scanmatch ?-nocase? contexthandle ?regexp? commands
Specify Tcl commands to be evaluated when regexp is matched by a scanfile command. The match is added to the scan context specified by contexthandle. Any number of match statements may be specified for a given context. Regexp is a regular expression (see the regexp command). If -nocase is specified as the first argument, the pattern is matched regardless of alphabetic case. ๐
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). So like... order matters, bestie. ๐ซถ
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. The 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. In addition, a set of procedures provide command access to the math functions supported by the expr command. Math girlies rise up, this is your moment. ๐
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. โจ
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 | seed ?seedval?
Generate a pseudorandom integer number greater than or equal to zero and less than limit. ๐ฒ
If seed is specified, then the command resets the random number generator to a starting point derived from the seedval. This allows one to reproduce pseudorandom number sequences for testing purposes. If seedval is 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. No cap, that's the chaotic energy we love. ๐
๐ LIST MANIPULATION COMMANDS ๐
Extended Tcl is out here giving you extra list manipulation commands and procedures, and honestly? It ate. ๐
intersect lista listb
Procedure that returns the logical intersection of two lists. The returned list will be sorted โ no messy vibes, it's organized bestie. โจ
intersect3 lista listb
Procedure that intersects two lists and hands you back a list containing three lists:
- The first list returned is everything in lista that wasn't in listb.
- The second list contains the intersection of the two lists.
- The third list contains all the elements that were in listb but weren't in lista.
The returned lists will be sorted. Three-for-one, we love a multitasker. ๐ซถ
lassign list var ?var...?
Assigns successive elements of a list to the specified variables. If there are more variable names than fields, the remaining variables get set to the empty string. If there are more elements than variables, you get a list of the unassigned elements returned. Fancy.
For example:
lassign {dave 100 200 {Dave Foo}} name uid gid longName
That assigns name to "dave", uid to "100", gid to "200", and longName to "Dave Foo". Slay, everyone's seated and accounted for. ๐
lcontain list element
Determines if the element is a list element of list. If the element is contained in the list, 1 is returned; otherwise, 0 is returned. Simple as. ๐
lempty list
Determines if the specified list is empty. If empty, 1 is returned; otherwise, 0 is returned. This command is an alternative to comparing a list to an empty string โ but here's the iconique part: it checks for a string of all whitespace, which counts as an empty list. No cap. ๐ฆ
lmatch ?mode? list pattern
Searches the elements of list, returning a list of all elements matching pattern. If none match, an empty list is returned. Sad girl hours, but correct.
The mode argument tells Tcl how the elements of the list are to be matched against pattern, and it must have one of these values:
-exactโ The list element must contain exactly the same string as pattern.-globโ Pattern is a glob-style pattern which is matched against each list element using the same rules as thestring matchcommand.-regexpโ Pattern is treated as a regular expression and matched against each list element using the same rules as theregexpcommand.
If mode is omitted then it defaults to -glob. ๐
Heads up bestie: only the -exact comparison will work on binary data. The other two said nah to binary. ๐
lrmdups list
Procedure that removes duplicate elements from a list. The returned list will be sorted. Decluttered, organized, healed. ๐ธ
lvarcat var string ?string...?
This command treats each string argument as a list and concatenates them to the end of the contents of var, forming a single list. The list is stored back into var and also returned as the result. If var does not exist, it is created. Growth mindset fr fr. ๐ฑ
lvarpop var ?indexExpr? ?string?
The lvarpop command pops (deletes) the element indexed by the expression indexExpr from the list contained in the variable var. If index is omitted, then 0 is assumed. If string is specified, then the deleted element is replaced by string. The replaced or deleted element is returned.
Thus lvarpop argv 0 returns the first element of argv, setting argv to contain the remainder of the string. Main character energy: takes the first one, keeps it, and just leaves. ๐ญ
If the expression indexExpr starts with the string end, then end is replaced with the index of the last element in the list. If the expression starts with len, then len is replaced with the length of the list.
lvarpush var string ?indexExpr?
The lvarpush command pushes (inserts) string as an element in the list contained in the variable var. The element is inserted before position indexExpr in the list. If index is omitted, then 0 is assumed. If var does not exist, it is created. Making room for you in the group chat. ๐ซถ
If the expression indexExpr starts with the string end, then end is replaced with the index of the last element in the list. If the expression starts with len, then len is replaced with the length of the list.
Note that a value of end means insert the string before the last element. Don't come for me, that's just what it does. ๐
union lista listb
Procedure that returns the logical union of the two specified lists. Any duplicate elements are removed. Two lists become one friend group. ๐
๐ KEYED LISTS ๐
Extended Tcl defines a special type of list referred to as keyed lists. These lists provide a structured data type built upon standard Tcl lists. It's giving functionality similar to structs in the C programming language, honestly.
A keyed list is a list in which each element contains a key and value pair. These element pairs are stored as lists themselves, where the key is the first element of the list and the value is the second. These key-value pairs are referred to as fields. Here's an example of a keyed list:
{{NAME {Frank Zappa}} {JOB {musician and composer}}}
If the variable person contained the above list, then keylget person NAME would return {Frank Zappa}. And if you execute this command:
keylset person ID 106
that would make person contain:
{{ID 106} {NAME {Frank Zappa}} {JOB {musician and composer}}
Fields may contain subfields; . is the separator character. Subfields are actually fields where the value is another keyed list. So the following list has the top level fields ID and NAME, and subfields NAME.FIRST and NAME.LAST:
{ID 106} {NAME {{FIRST Frank} {LAST Zappa}}}
There is no limit to the recursive depth of subfields, allowing you to build complex data structures. It's turtles all the way down bestie. ๐ขโจ
Keyed lists are constructed and accessed via a number of commands. All keyed list management commands take the name of the variable containing the keyed list as an argument (i.e. passed by reference), rather than passing the list directly. Important detail, don't forget it. ๐
keyldel listvar key
Deletes the field specified by key from the keyed list in the variable listvar. This removes both the key and the value from the keyed list. Blocked and deleted, respectfully. ๐
keylget listvar ?key? ?retvar | {}?
Returns the value associated with key from the keyed list in the variable listvar. If retvar is not specified, then the value will be returned as the result of the command. In this case, if key is not found in the list, an error will result. ๐ฌ
If retvar is specified and key is in the list, then the value is returned in the variable retvar and the command returns 1 if the key was present within the list. If key isn't in the list, the command will return 0, and retvar will be left unchanged. If {} is specified for retvar, the value is not returned, allowing the Tcl programmer to determine if a key is present in a keyed list without setting a variable as a side-effect. No sneaky side effects, we love a clean boundary. ๐ง
If key is omitted, then a list of all the keys in the keyed list is returned.
keylkeys listvar ?key?
Returns a list of the keys in the keyed list in the variable listvar. If keys is specified, then it is the name of a key field whose subfield keys are to be retrieved. Yes bestie, keys within keys. ๐
keylset listvar key value ?key2 value2 ...?
Sets the value associated with key, in the keyed list contained in the variable listvar, to value. If listvar does not exist, it is created. If key is not currently in the list, it will be added. If it already exists, value replaces the existing value. Multiple keywords and values may be specified, if desired โ go off, set them all at once. ๐ฅ๐
โจ STRING AND CHARACTER MANIPULATION COMMANDS โจ
okay bestie, this whole section is the glow-up era for strings ๐
these commands let you classify characters, convert characters between character and numeric values, index into a string, figure out the length of a string, pull out a range of characters from a string, replicate a string a bunch of times, and transliterate a string (basically the Unix tr program's cousin, iykyk). so many little icons, all here for you ๐
ccollate ?-local? string1 string2โ compares two strings, periodt. it 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 returns the resulting string. normally the parser handles string concatenation, but sometimes it's genuinely useful to have a command that returns a string โ it's generally useful when a command to evaluate is required. and ngl, no separators get inserted between the strings, so it's giving clean seamless slay โจ
this command is UTF-aware ๐ฆ
cequal string stringโ compares two strings for equality, no notes. returns1if string1 and string2 are the identical and0if they're not. it's a short-cut forstring compareand avoids the problems that come with string expressions being treated unintentionally as numbers ๐
this command is UTF-aware and will also work on binary data ๐ฅ
cindex string indexExprโ returns the character indexed by the expression indexExpr (zero based) from string.
if the expression indexExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string. the way that just works ๐ง
this command is UTF-aware ๐
clength stringโ returns the length of string in characters. it's literally just a shortcut for:
string length string
this command is UTF-aware โจ
crange string firstExpr lastExprโ returns a range of characters from string starting at the character indexed by the expression firstExpr (zero-based) until the character indexed by the expression lastExpr.
if the expression firstExpr or lastExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string.
this command is UTF-aware ๐ธ
csubstr string firstExpr lengthExprโ returns a range of characters from string starting at the character indexed by the expression firstExpr (zero-based) for lengthExpr characters.
same deal as before: if the expression firstExpr or lengthExpr starts with the string end, then end is replaced with the index of the last character in the string. if the expression starts with len, then len is replaced with the length of the string.
this command is UTF-aware ๐
ctoken strvar separatorsโ parses a token out of a character string. the string to parse lives in the variable named strvar, and separators contains all of the valid separator characters for tokens in the string. all leading separators get skipped and the first token is returned. strvar then gets modified to contain the remainder of the string following the token ๐ซถ
no cap, this command does not work with binary data ๐
๐ ctype โ the character-classification queen ๐
ctype ?-failindex var? class stringโ determines whether all characters in string are of the specified class. returns1if they're all of class, and0if they're not, or if the string is empty. this command also gives you another method (besidesformatandscan) of converting between an ASCII character and its numeric value ๐งฎ
the following ctype commands are available:
ctype ?-failindex var? alnum stringโ tests that all characters are alphabetic or numeric characters as defined by the character set.ctype ?-failindex var? alpha stringโ tests that all characters are alphabetic characters as defined by the character set.ctype ?-failindex var? ascii stringโ tests that all characters are an ASCII character (a non-negative number less than0200).ctype char numberโ converts the numeric value, string, to an ASCII character. Number must be in the range0through the maximum Unicode values.ctype ?-failindex var? cntrl stringโ tests that all characters are "control characters" as defined by the character set.ctype ?-failindex var? digit stringโ tests that all characters are valid decimal digits, i.e.0through9.ctype ?-failindex var? graph stringโ tests that all characters within are any character for whichctype printis true, except for space characters.ctype ?-failindex var? lower stringโ tests that all characters are lowercase letters as defined by the character set.ctype ord characterโ converts a character into its decimal numeric value. the first character of the string is converted to its numeric Unicode value.ctype ?-failindex var? space stringโ tests that all characters are either a space, horizontal-tab, carriage return, newline, vertical-tab, or form-feed.ctype ?-failindex var? print stringโ tests that all characters are a space or any character for whichctype alnumorctype punctis true or other "printing character" as defined by the character set.ctype ?-failindex var? punct stringโ tests that all characters are made up of any of the characters other than the ones for whichalnum,cntrl, orspaceis true.ctype ?-failindex var? upper stringโ tests that all characters are uppercase letters as defined by the character set.ctype ?-failindex var? xdigit stringโ tests that all characters are valid hexadecimal digits, that is0through9,athroughforAthroughF.
if -failindex is specified, then the index into string of the first character that did not match the class is returned in var ๐
lowkey so useful for debugging.
replicate string countExprโ returns string, replicated the number of times indicated by the expression countExpr. it's giving copy-paste but make it fashion โจ
this command is UTF-aware and will work with binary data ๐ฅ
translit inrange outrange stringโ translates characters in string, changing characters occurring in inrange to the corresponding character in outrange. inrange and outrange may be a list of characters or a range in the formA-M. for example:
translit a-z A-Z foobar
bestie, real talk: this command currently only supports characters in ASCII range; UTF-8 characters out of this range will generate an error ๐
โจ XPG/3 MESSAGE CATALOG COMMANDS โจ
Okay bestie, this is the message-catalog era of the page, and itโs genuinely iconic for anyone who wants their app to speak every language without rewriting source code every five minutes. These commands give you a Tcl interface to message catalogs that are compliant with the X/Open Portability Guide, Version 3 (XPG/3). ๐
Tcl programmers can use message catalogs to create applications that are language-independent. Through message catalogs, prompts, messages, menus and so forth can exist for any number of languages, and they can be altered, and new languages added, without affecting any Tcl or C source code โ which greatly eases the maintenance difficulties incurred by supporting multiple languages. Slay, honestly. ๐
A default text message is passed to the command that fetches entries from message catalogs. This lets the Tcl programmer create message catalogs containing messages in various languages while still having a set of default messages available regardless of whether any message catalogs are present โ and it lets programs press on without difficulty when no catalogs are present. ๐ซถ
So the normal approach to using message catalogs is to ignore errors on catopen, in which case catgets will return the default message that was specified in the call.
The Tcl message catalog commands normally ignore most errors. If itโs desirable to detect errors, a special option is provided. This is normally used only during debugging, to insure that message catalogs are being used. If your Unix implementation does not have XPG/3 message catalog support, stubs will be compiled in that will create a version of catgets that always returns the default string. That allows for easy porting of software to environments that donโt have support for message catalogs. ๐
Message catalogs are global to the process, so an application with multiple Tcl interpreters within the same process may pass and share message catalog handles. No cap.
catopen ?-fail | -nofail? catnameโ Opens the message catalogcatname. This may be a relative path name, in which case theNLSPATHenvironment variable is searched to find an absolute path to the message catalog. A handle in the formmsgcatNis returned. Normally, errors are ignored, and in the case of a failed call tocatopen, a handle is returned to an unopened message catalog. That handle may still be passed tocatgetsandcatclose, causingcatgetsto simply return the default string, as described above. If the-failoption is specified, an error is returned if the open fails. The option-nofailspecifies the default behavior of not returning an error whencatopenfails to open a specified message catalog. If the handle from a failedcatopenis passed tocatgets, the default string is returned. ๐catgets catHandle setnum msgnum defaultstrโ Retrieves a message from a message catalog.catHandleshould be a Tcl message catalog handle that was returned bycatopen.setnumis the message set number, andmsgnumis the message number. If the message catalog was not opened, or the message set or message number cannot be found, then the default string,defaultstr, is returned. Lowkey the most forgiving lookup ever. ๐ญcatclose ?-fail | -nofail? cathandleโ Closes the message catalog specified bycathandle. Normally, errors are ignored. If-failis specified, any errors closing the message catalog file are returned. The option-nofailspecifies the default behavior of not returning an error. The use of-failonly makes sense if it was also specified in the call tocatopen. Periodt.mainloopโ This procedure sets up a top-level event loop. Events are processed until there are no more active event sources, at which time the process exits. It is used to build event-oriented programs using the TclX shell in a style similar to that used withwish. If the global variabletcl_interactiveexists and has a true value, an interactive command handler is started as well. If the command handler is terminated by an EOF, the process will be exited. Main character energy for event loops, honestly. ๐
๐ธ HELP FACILITY ๐ธ
The help facility lets you look up help pages which 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. Help files are found by searching directories named help in the directories listed in the auto_path variable. All of the files in the list of help directories form a virtual root of the help tree. This method allows multiple applications to provide help trees without having the files reside in the same directory. So clever. ๐ง
The help facility can be accessed in two ways: as interactive commands in the Extended Tcl shell, or as an interactive Tk-based program (if you have built Extended Tcl with Tk).
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. This will result in help on Tcl, Extended Tcl and Tk. ๐
The following interactive Tcl commands and options are provided with the help package:
helpโ Help, without arguments, lists all the help subjects and pages under the current help subject.help subjectโ Displays all of the help pages and lower level subjects (if any exist) under the subjectsubject.help subject/helppageโ Displays the specified help page. The help output is passed through a simple pager if output exceeds 23 lines, pausing waiting for a return to be entered. If any other character is entered, the output is terminated. Very โread it or skip itโ of it. ๐helpcd ?subject?โ Changes the current subject, which is much like the Unix current directory. Ifsubjectis not specified, return 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. Meta, but make it cute. ๐ฆapropos patternโ This command locates subjects by searching their one-line descriptions for a pattern.aproposis useful when you can 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). Obsessed with a good search moment. ๐ฅ
๐ TCL LOADABLE LIBRARIES AND PACKAGES ๐
Extended Tcl supports standard Tcl tclIndex libraries and package libraries. A package library file can contain multiple independent Tcl packages. A package is a named collection of related Tcl procedures and initialization code. Think of it as a little friend group of procedures, ngl.
The package library file is just a regular Unix text file, editable with your favorite text editor, containing packages of Tcl source code. The package library file name must have the suffix .tlib. An index file with the same prefix name and the suffix .tndx resides in the same directory as the .tlib file. The .tndx will be automatically created whenever it is out of date or missing (provided there is write access to the directory). Iconic little auto-maintenance behavior. โจ
The variable auto_path contains a list of directories that are searched for libraries. The first time an unknown command trap is taken, the indexes for the libraries are loaded into memory. If the auto_path variable is changed during execution of a program, it will be re-searched. Only the first package of a given name found during the execution of a program is loaded. This can be overridden with the loadlibindex command. Okay, noted. ๐
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 is executed and detected as an unknown command, all code in the specified package will be sourced. This package should define all of the procedures named on the package line, define any support procedures required by the package and do any package-specific initialization. Package declarations may be continued on subsequent lines using standard Tcl backslash line continuations. The #@packend keyword is useful to make sure only the minimum required section of code is sourced. Thus, for example, a large comment block at the beginning of the next file wonโt be loaded. So efficient. ๐
Care should be taken in defining package_name, as the first package found in the path with a given name is loaded. This can be useful in developing new versions of packages installed on the system. Big โtest your new version without chaosโ energy. ๐
For example, in a package source file, the presence of the following 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 is a package named directory_stack, and that an attempt to execute either pushd, popd or dirs when the routine is not already defined will cause the directory_stack portion of the package file to be loaded. And thatโs literally the whole vibe of package entry points. ๐
๐ PACKAGE LIBRARY MANAGEMENT COMMANDS ๐
okay so this is the part where we talk about building and managing package libraries โ like, the whole infrastructure of it ๐ there's a bunch of commands for it, and the ones that are extended versions of the standard Tcl library commands are the ones listed here. also important: every single standard Tcl library management command and variable is supported too, so don't come for me thinking they got left out, they're just not re-explained here, iykyk โจ
auto_commands?-loaders? โ lists the names of all known loadable procedures and command procedures. and if you pass-loaders, it also hands you back the command that will be executed to load the command ๐ซถbuildpackageindexlibfilelist โ builds index files for package libraries. libfilelist is a list of package libraries, and every name has to end with the suffix.tlibor it's a no. for each one, a corresponding.tndxfile gets built. heads up: you must have write access to the directory containing each library, otherwise this whole thing is not happening bestie ๐ญconvert_libtclIndex packagelib ?ignore? โ converts an old-school Ousterhout styletclIndexindex file plus its associated source files into a package library called packagelib. if packagelib doesn't have a.tlibextension, one gets added for you, slay. any files listed in tclIndex that are also in the ignore list get skipped. and listen โ files in ignore should be just the base file names, not full paths โญloadlibindexlibfile.tlib โ loads the package library index of the library file libfile (which must have the.tlibsuffix). so here's the vibe: package library indexes along theauto_pathget loaded automatically on the firstdemand_load, and this command exists for when you wanna explicitly load libraries that aren't in the path. if the index file (with the.tndxsuffix) doesn't exist or is out of date, it gets rebuilt โ but only if you've got the directory permissions to create it ๐ also: if a package with the same name as one in libfile.tlib is already loaded, its definition gets overridden by the new package. however (and this is the big however ๐), if any procedure from the previously defined package has actually been used, then the procedures from libfile.tlib will not be loaded. no cap, that's the rule.auto_packages?-location? โ returns a list of the names of all defined packages ๐ and if you throw-locationin there, you get a list of pairs: package name plus the.tlibpath name, offset and length of the package within the library. chef's kiss, so much info.auto_load_filefile โ sources a file exactly like thesourcecommand does, except it searchesauto_pathfor the file instead of making you spell out where it lives. main character energy honestly ๐searchpathpath file โ searches every directory in the specified path (which is a Tcl list) for the specified file, and returns the full path name of the file. if the file you asked for can't be found? you get an empty string back, and that's just how it is ๐ฆ
auto_commands ?-loaders?
buildpackageindex libfilelist
convert_lib tclIndex packagelib ?ignore?
loadlibindex libfile.tlib
auto_packages ?-location?
auto_load_file file
searchpath path file
ok genuine heads up bestie: loadlibindex has real consequences โ overriding a package definition is fine right up until somebody has used a proc from the old one, and then nothing from the new library loads. plan around it, don't be surprised by it ๐
and that's a wrap on the whole page!! ๐โจ this was the TclX(TCL) page from the Tcl manual set โ you made it all the way to the end, so proud of you fr fr ๐ซถ go build something iconic with it, mwah ๐
๐ฆ where this page comes from
- alpine 3.24: tclx-doc 8.6.3-r1 ยท BSD
- nixos 26.05: tclx 8.6.3
- nixpkgs unstable: tclx 8.6.3
- Copyright 1992-1999 Karl Lehenbauer and Mark Diekhans
- Copyright 2004 ActiveState Corporation
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms