|
|
|
|
Tcl/Tk in a NutshellBy Paul Raines & Jeff Tranter1st Edition March 1999 1-56592-433-9, Order Number: 4339 456 pages, $24.95 |
Sample Chapter 10:
TclX (continued)
Click here for first part of the sample chapter.
double
doublearg
Evaluate the expression
arg, convert the result to floating-point, and return the converted value.dup
dupfileId[targetFileId]
Create a new file identifier that refers to the same device as the open file identifier
fileId. The new file identifier is returned.Can optionally specify the name of an existing file identifier
targetFileId(normallystdin,stdout, orstderr). In this case thetargetFileIddevice is closed if necessary, and then becomes a duplicate that refers to the same device asfileId.On Windows, only
stdin,stdout,stderr, or a nonsocket file handle number may be specified fortargetFileId.echo
echo [string...]
Write zero or more strings to standard output, followed by newline character.
edprocs
edprocs [proc...]
Write the definitions for the named procedures (by default, all currently defined procedures) to a temporary file, invoke an editor, then reload the definitions if they were changed. Uses the editor specified by the EDITOR environment variable, or vi > if none is specified.
execl
execl [-argv0argv0]prog[arglist]
Perform an execl > system call, replacing the current process with program
progand the arguments specified in the listarglist. The command does not return unless the system call fails.The -argv0 > option specifies the value to be passed as
argv[0]of the new program.Under Windows, the execl command starts a new process and returns the process ID.
exp
exparg
Return the value of the constant e raised to the power of the expression
arg.fcntl
fcntlfileIdattribute[value]
Modifiy or return the current value of a file option associated with an open file identifier. If only
attributeis specified, its current value is returned. If a booleanvalueis specified, the attribute is set. Some values are read only. The following attributes may be specified:
RDONLYFile is opened for reading (read only).
WRONLYFile is opened for writing (read only).
RDWRFile is opened for reading and writing (read only).
READFile is readable (read only).
WRITEFile is writable (read only).
APPENDFile is opened for appending.
NONBLOCKFile uses nonblocking I/O.
CLOEXECClose the file upon execution of a new process.
NOBUFFile is not buffered.
LINEBUFFile is line buffered.
KEEPALIVEKeep-alive option is enabled for a socket.
The
APPENDandCLOEXECattributes are not available on Windows.flock
flockoptionsfileId[start] [length] [origin]
Place a lock on all or part of the file open with identifier
fileId. The file data is locked from the beginning of byte offsetstartfor a length oflengthbytes. The default start position is the start of file, and the default length is to the end of file. If the file is currently locked, the command waits until it is unlocked before returning.The value of
originindicates the offset for the data locked and is one of the stringsstart(relative to start of file, the default),current(relative to the current access position), orend(relative to end of file, extending backward).This command is not supported on Windows 95/98. Also see funlock >.
Options
- -read
Place a read lock on the file.
- -write
Place a write lock on the file.
- -nowait
Do not block if lock cannot be obtained. Return 1 if the file could be locked, or 0 if it could not.
floor
floorarg
Return the value of expression
argrounded down to the nearest integer.fmod
fmodxy
Return the remainder after dividing expression
xby expressiony.for_array_keys
for_array_keysvararray_namecode
Perform a foreach >-style loop for each key in the array
array_name.Example
for_array_keys key tcl_platform { echo $key => $tcl_platform($key) }for_file
for_filevarfilenamecode
Loop over the file
filename, settingvarto the line and executingcodefor each line in the file.Example
for_file line /etc/passwd { echo $line }for_recursive_glob
for_recursive_globvardirlistgloblistcode
Perform a foreach >-style loop over files that match patterns. All directories in the list
dirlistare recursively searched for files that match the glob patterns in listgloblist. For each matching file the variablevaris set to the file path and codecodeis evaluated.Example
for_recursive_glob file {~ /tmp} {*.tcl *.c *.h} { echo $file }fork
fork
Call the fork > system call to duplicate the current process. Returns 0 to the child process, and the process number of the child to the parent process. This command is not supported under Windows.
fstat
fstatfileId[item] | [stat >arrayvar]
Return status information about the file opened with identifier
fileId. If one of the keys listed below is specified, the data for that item is returned. If stat >arrayvaris specified, the information is written into arrayarrayvarusing the listed keys. If only a file identifier is specified, the data is returned as a keyed list.The following keys are used:
atimeTime of last access.
ctimeTime of last file status change.
devDevice containing a directory for the file.
gidGroup ID of the file's group.
inoInode number.
modeMode of the file.
mtimeTime of last file modification.
nlinkNumber of links to the file.
sizeSize of file in bytes.
tty1 if the file is associated with a terminal, otherwise 0.
typeType of the file, which can be
file,directory,characterSpecial,blockSpecial,fifo,link, orsocket.uidUser ID of the file's owner.
The following additional keys may be specified, but are not returned with the array or keyed list forms:
remotehostIf
fileIdis a TCP/IP socket connection, a list is returned, with the first element being the remote host IP address. If the remote hostname can be found, it is returned as the second element of the list. The third element is the remote host IP port number.localhostIf
fileIdis a TCP/IP socket connection, a list is returned, with the first element being the local host IP address. If the local hostname can be found, it is returned as the second element of the list. The third element is the local host IP port number.ftruncate
ftruncate [-fileId]filenewsize
Truncate a file to a length of at most
newsizebytes. With the -fileId option, thefileargument is an open file identifier rather than a filename. The -fileId option is not available on Windows.funlock
funlockfileId[start] [length] [origin]
Remove a file lock that was previously set using an flock > command on the file open with identifier
fileId. The portion of the file data that is locked is from the beginning of byte offsetstartfor a length oflengthbytes. The default start position is the start of file, and the default length is to the end of file.The value of
originindicates the offset for the locked data and is one of the stringsstart(relative to start of file, the default),current(relative to the current access position), orend(relative to end of file).This command is not supported on Windows 95/98. Also see flock >.
help
help [options]
Invoke the online Tcl help facility to provide information on all Tcl and Extended Tcl commands. Information is structured as a hierarchical tree of subjects with help pages at the leaf nodes. Without arguments, the command lists all of the help subjects and pages under the current help subject.
- help >
subjectDisplay all help pages and lower-level subjects (if any) under the subject
subject.- help >
subject/helppageDisplay the specified help page.
- help > help >|?
Display help on using the help facility itself. Valid at any directory level.
helpcd
helpcd [subject]
Change the current subject in the hierarchical tree of help information. Without a
subject, goes to the top level of the help tree.helppwd
helppwd
Display the current subject in the hierarchical documentation tree of online help information.
host_info
host_infooptionhost
Return information about a network host. The command takes one of the following three forms:
- host_info addresses >
hostReturn a list of the IP addresses for
host.- host_info official_name >
hostReturn the official name for
host.- host_info aliases >
hostReturn a list of aliases for
host.hypot
hypotxyid
idoptions
Provides various functions related to getting, setting, and converting user, group, and process identifiers. Some functions can be performed only by the superuser. Under Windows only the host > and process > options are implemented.
Without a
nameoption, return the current username. With an option, sets the real and effective user toname.Without a
uidoption, return the current numeric user ID. With an option, set the real and effective user touid.Return the username corresponding to numeric user ID
uid.Return the numeric user ID corresponding to user
name.Without a
nameoption, return the current group ID name. With an option, set the real and effective group ID toname.Without a
gidoption, return the current numeric group ID. With an option, set the real and effective group ID togid.Return a list of group names for the current process.
Return a list of numeric group IDs for the current process.
Return the group name corresponding to numeric group ID
gid.Return the numeric group ID corresponding to group
name.Return the effective username.
Return the effective user ID number.
Return the effective group name.
Return the effective group ID number.
Return the hostname of the system on which the program is running.
Return the process ID of the current process.
Return the process ID of the parent of the current process.
Return the process group ID of the current process.
Set the process group ID of the current process to its process ID.
infox
infoxoption
Return information about the Extended Tcl interpreter or current application. The command can take the following forms:
Return the Extended Tcl version number.
Return the Extended Tcl patch level.
Return 1 if the fchown > system call is available otherwise. If available, the -fileId > option on the chown > and chgrp > commands is supported.
Return 1 if the fchmod > system call is available otherwise. If available, the -fileId > option on the chmod > command is supported.
Return 1 if the flock > command is defined, 0 if it is not available.
Return 1 if the fsync > system call is available and the sync > command will sync individual files, 0 if fsync > is not available and the sync > command will always sync all file buffers.
Return 1 if the ftruncate > or chsize > system call is available. If it is, the ftruncate > command -fileId > option may be used.
Return 1 if XPG message catalogs are available, 0 if they are not. The catgets > command is designed to continue to function without message catalogs, always returning the default string.
Return 1 if POSIX signals (block > and unblock > options for the signal > command) are available.
Return 1 if the truncate > system call is available. If it is, the ftruncate > command may truncate by file path.
Return 1 if the waitpid > system call is available and the wait > command has full functionality, 0 if the wait > command has limited functionality.
Return the symbolic name of the current application linked with the Extended Tcl library. The C variable
tclAppNamemust be set by the application to return an application-specific value for this variable.Return a natural language name for the current application. The C variable
tclLongAppNamemust be set by the application to return an application-specific value for this variable.Return the version number for the current application. The C variable
tclAppVersionmust be set by the application to return an application-specific value for this variable.Return the patch level for the current application. The C variable
tclAppPatchlevelmust be set by the application to return an application-specific value for this variable.int
intarg>
Evaluate the expression
arg, convert the result to an integer, and return the converted value.intersect
intersectlist1list2
Return the logical intersection of two lists, i.e., a list of all elements contained in both
list1andlist2. The returned list is sorted alphabetically.intersect3
intersect3list1list2
Return a list containing three lists. The first consists of all elements of
list1that are not inlist2. The second contains the intersection of the two lists. The third contains all elements oflist2that are not inlist1. The returned lists are sorted alphabetically.keyldel
keyldellistvarkey
Delete the field specified by
keyfrom the keyed list in variablelistvar. Removes both the key and the value from the keyed list.keylget
keylgetlistvar[key] [retvar|{}]
Return the value associated with
keyfrom the keyed list in variablelistvar. Ifretvaris not specified, the value will be returned as the result of the command. In this case, ifkeyis not found in the list, an error will result.If
retvaris specified andkeyis in the list, the value is returned in the variableretvarand the command returns 1 if the key was present within the list. Ifkeyis not in the list, the command will return 0, andretvarwill be left unchanged. If {} is specified forretvar, the value is not returned, allowing the programmer to determine if a key is present in a keyed list without setting a variable as a side effect.If
keyis omitted, a list of all the keys in the keyed list is returned.keylkeys
keylkeyslistvar[key]
Return a list of the keys in the keyed list contained in variable
listvar. Ifkeyis specified, it is used as the name of a key field whose subfield keys are to be retrieved.keylset
keylsetlistvarkeyvalue...
Set the value associated with
keytovaluein the keyed list contained in variablelistvar. Iflistvardoes not exist, it is created. Ifkeyis not currently in the list, it is added. If it already exists,valuereplaces the existing value. Multiple keywords and values may be specified if desired.kill
kill [-pgroup] [signal]idlist
Send a signal to each process in the list
idlist, if permitted. Parametersignal, if present, is the signal number or symbolic name of the signal. The default is 15 (SIGTERM).If -pgroup > is specified, the numbers in
idlistare taken as process group IDs and the signal is sent to all of the processes in that process group. A process group ID of 0 specifies the current process group. This command is not supported under Windows.lassign
lassignlistvar...
Assign successive elements of a list to specified variables. If there are more variable names than fields, the remaining variables are set to the empty string. If there are more elements than variables, a list of the unassigned elements is returned.
lcontain
lcontainlistelement
Return 1 if
elementis an element of listlist; otherwise, return 0.lempty
lemptylist
Return 1 if
listis an empty list; otherwise, return 0.lgets
lgetsfileId[varName]
Read a Tcl list from the file given by file identifier
fileId, discarding the terminating newline. IfvarNameis specified, the command writes the list to the variable and returns the number of characters read; otherwise, it returns the list.link
link [-sym]srcpathdestpath
Create a link from existing pathname
srcpathtodestpath. With option -sym >, creates a symbolic rather than hard link. This command is not supported under Windows.lmatch
lmatch [mode]listpattern
Return a new list, consisting of the elements of
listthat matchpattern. The type of pattern matching is determined by themodeparameter:
- -exact
Exact match
- -glob
Glob-style matching (default)
- -regexp
Regular expression matching
loadlibindex
loadlibindexlibfile.tlib
Load the package library index of the library file
libfile.tlib.log
logarg
Return the natural logarithm of expression
arg.log10
log10arg
Return the base 10 logarithm of expression
arg.loop
loopvarfirstlimit[increment]body
Loop construct in which the beginning and ending loop index variables and increment are fixed. The loop index is variable
var, which is initialized tofirst. In each iteration of the loop, if the index is not equal tolimit, the commandbodyis evaluated and the index is increased by the valueincrement.Example
# count from ten down to one loop i 10 0 -1 { echo $i }lrmdups
lrmdupslist
Remove duplicate elements from
list; return the result, sorted alphabetically.lvarcat
lvarcatvarstring...
Concatenate one or more string arguments to the end of the list contained in variable
var, storing the result invarand returning the resulting list. String arguments that are lists are deconstructed into individual elements before being concatenated into the result list.lvarpop
lvarpopvar[indexExpr] [string]
Remove the element of the list contained in
varhaving indexindexExpr(default 0). Ifstringis given, the deleted element is replaced with the string. Returns the replaced or deleted item.Indices start at 0, and the words
endandlencan be used at the beginning of the expression to indicate the index of the last element and length of the list, respectively.lvarpush
lvarpushvarstring[indexExpr]
Insert
stringas an element of the list stored invarbefore positionindexExpr(default 0).Indices start at 0, and the words
endandlencan be used at the beginning of the expression to indicate the index of the last element and length of the list, respectively.mainloop
mainloop
Start a top-level event handler. Process events until there are no more active event sources, then exit.
max
maxnumber...
Return the argument having the highest numeric value. The arguments can be any mixture of integer or floating-point values.
min
minnumber...
Return the argument having the lowest numeric value. The arguments can be any mixture of integer or floating-point values.
nice
nice [priorityIncr]
Without arguments, return the current process priority. With a numeric argument, add
priorityIncrto the current process priority. A negative value increases the process priority (this will work only for the superuser). This command is not supported under Windows.pipe
pipe [fileId_var_rfileId_var_w]
Create a pipe. Without options, return a list containing the file identifiers for the read and write ends of the pipe. If passed two variable names, they are set to the file identifiers for the opened pipe.
popd
popd
Remove the top entry from the directory stack; make it the current directory.
pow
powxya>
Return the value of expression
xraised to the power of expressiony.profile
profile [-commands] [-eval] on >
Start collection of data for performance profiling of procedures. With the -commands option, also profiles commands within a procedure. With the -eval option, uses the procedure call stack rather than the procedure scope stack when reporting usage.
Turn off profiling and store the results in variable
arrayVarfor later analysis by the profrep command.profrep
profrep >profDataVarsortKey[outFile] [userTitle]
Generate a report using profile data generated by the profile command. Data must have been previously stored in variable
profDataVar. The parametersortKeyhas one of the valuescalls,cpu, orreal, indicating how to sort the output. The output can optionally be written to fileoutFile(default is standard out) using an optional titleuserTitle.pushd
pushd [dir]
Push the current directory onto the directory stack and change to directory
dir. If no directory is specified, the current directory is pushed but remains unchanged.random
randomlimit
Return a pseudorandom integer greater than or equal to 0 and less than
limit.Reset the random number generator using the number
seedval, or if omitted, a seed based on the current date and time.read_file
read_file [-nonewline]fileName[numBytes]
Read the entire contents of file
fileNameand return it as a string. The -nonewline > option discards any final newline character in the file. ThenumBytesoption specifies the number of bytes to read.readdir
readdir [-hidden]dirPath
Return a list of the files contained in directory
dirPath. The option -hidden > causes hidden files to be included in the list (Windows platforms only).recursive_glob
recursive_globdirlistgloblist
Recursively search the directories in list
dirlistfor files that match any of the patterns ingloblist. Returns a list of matching files.replicate
replicatestringcountExpr
Return
stringreplicated the number of times indicated by integer expressioncountExpr.round
roundarg
Evaluate the expression
arg, convert the result to an integer by rounding, and return the converted value.saveprocs
saveprocsfileName[proc...]
Save the definitions of the listed Tcl procedures (by default, all procedures) to file
fileName.scancontext
scancontext [option]a name="scanfile">
Create, delete, or modify file scan contexts.
Create a new scan context.
scancontext delete >
contexthandleDelete the scan context identified by
contexthandle.scancontext copyfile >
contexthandleReturn the file handle to which unmatched lines are copied.
scancontext copyfile >
contexthandle[filehandle]Set the file handle to which unmatched lines are copied. A file handle of
{}removes any file copy specification.scanfile
scanfile< [-copyfilecopyFileId]contexthandlefileId
Scan the file specified by
fileIdstarting from the current file position. Check all patterns in the scan context specified bycontexthandle, 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.
scanmatch
scanmatch [-nocase]contexthandle[regexp]commands
Specify Tcl commands to be evaluated when
regexpis matched by a scanfile > command. The match is added to the scan context specified bycontexthandle. Any number of match statements may be specified for a given context. With option -nocase >, the pattern matching is case insensitive.searchpath
searchpathpathListfile
Search the directories in list
pathListfor filefile. Return the full path if found; otherwise, return an empty string.select
selectreadfileIds[writefileIds] [exceptfileIds] [timeout]
Wait for a change of status in file identifiers. Up to three lists, containing file identifiers for files to be polled for read, write, or exceptions, can be specified. An optional parameter
timeoutindicates the maximum time, in seconds, to wait (it can be 0 for polling). The command returns three lists, corresponding to the file descriptors in each of the three categories that have a change in status.On Windows, only sockets can be used with the select > command.
showproc
showproc [procname...]
List the definitions of the named Tcl procedures (by default, all procedures).
signal
signalactionsiglist[command]
Set the action to take when a Unix signal is received. The
siglistparameter lists one or more signal names or numbers. Parameteractionindicates the action to take, as described in the following:
- default >
Take system default action.
- ignore >
Ignore the signal.
- error >
Generate a catchable Tcl error.
- trap >
Execute command indicated by
commandparameter.- get >
Return current settings for the specified signals as a keyed list.
- set >
Set signals from a keyed list in the format returned by get >.
- block >
Block signals from being received.
- unblock >
Allow the specified signal to be received.
sin
sinarg
Return the sine of expression
arg.sinh
sinharg
Return the hyperbolic sine of expression
arg.sleep
sleepseconds
Delay execution of the current process for
secondsseconds, which must be an integer value.sqrt
sqrtarg
Return the square root of expression
arg.sync
sync [fileId]
With no options, issue a sync > system call to write pending data to disk. With a file identifier
fileIdcorresponding to a file open for writing, schedule output for that file to disk. On platforms that do not support the fsync > system call, thefileIdparameter is ignored.system
systemcmdstring...
Concatenate one or more command strings with space characters and execute the command using the system command interpreter (/bin/sh on Unix and command.com on Windows). Returns the numeric return code of the command.
tan
tanarg
Return the tangent of expression
arg.tanh
tanharg
Return the hyperbolic tangent of expression
arg.tclx_errorHandler
tclx_errorHandlermessage
A user-written procedure to handle errors. Called before returning to the top-level command interpreter after an unhandled error.
times
times
Return a list containing four process CPU usage time values, in the form
utimestimecutimecstime.translit
translitinrangeoutrangestring
Transliterate characters in
string, replacing the characters occurring ininrangeto the corresponding characters inoutrange. The ranges may be lists of characters or a range in the formlower-upper.Example
translit a-z A-Z "A string"try_eval
try_evalcodecatch[finally]
Evaluate the command string
code. If an error occurs, evaluatecodeand return the result. Last, execute the command stringfinally.Example
try_eval { # code puts -nonewline stderr "Enter a number: " set ans [gets stdin] # could fail, e.g. due to divide by zero set res [expr 1.0 / $ans] puts stderr "1 / $ans = $res" } { # catch set msg [lindex $errorCode end] puts stderr "Error: $msg" } { # finally puts stderr "End of example" }umask
umask [octalmask]
Set the file creation mode mask to
octalmask, which must be an octal (base 8) number. With no parameters, return the current mask.union
unionlist1list2
Return the logical union of two lists, i.e., a list of all elements contained in either
list1orlist2. The returned list is sorted alphabetically and has no duplicate elements.wait
wait [-nohang] [-untraced] [-pgroup] [pid]
Wait for a child process with process ID
pidto terminate (or any process ifpidis omitted).Options
- -nohang
Don't block waiting on the process to terminate.
- -untraced
Return status of other child processes.
- -pgroup
Wait on any processes in process group.
The command returns a list with three elements: the process ID of the process that terminated, the reason code (EXIT >, SIG >, SIGSTP >, or STOP >), and the numeric exit code.
write_file
write_filefileNamestring...
Write one or more strings to the file named
fileName. Each string is terminated with a newline character.
© 2001, O'Reilly & Associates, Inc.