Search the Catalog
Tcl/Tk in a Nutshell

Tcl/Tk in a Nutshell

By Paul Raines & Jeff Tranter
1st 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

double arg

Evaluate the expression arg, convert the result to floating-point, and return the converted value.

dup

dup fileId
[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 (normally stdin, stdout, or stderr). In this case the targetFileId device is closed if necessary, and then becomes a duplicate that refers to the same device as fileId.

On Windows, only stdin, stdout, stderr, or a nonsocket file handle number may be specified for targetFileId.

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 [-argv0 argv0]
prog [arglist]

Perform an execl > system call, replacing the current process with program prog and the arguments specified in the list arglist. 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

exp arg

Return the value of the constant e raised to the power of the expression arg.

fcntl

fcntl fileId
attribute
[value]

Modifiy or return the current value of a file option associated with an open file identifier. If only attribute is specified, its current value is returned. If a boolean value is specified, the attribute is set. Some values are read only. The following attributes may be specified:

RDONLY

File is opened for reading (read only).

WRONLY

File is opened for writing (read only).

RDWR

File is opened for reading and writing (read only).

READ

File is readable (read only).

WRITE

File is writable (read only).

APPEND

File is opened for appending.

NONBLOCK

File uses nonblocking I/O.

CLOEXEC

Close the file upon execution of a new process.

NOBUF

File is not buffered.

LINEBUF

File is line buffered.

KEEPALIVE

Keep-alive option is enabled for a socket.

The APPEND and CLOEXEC attributes are not available on Windows.

flock

flock options
fileId [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 offset start for a length of length bytes. 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 origin indicates the offset for the data locked and is one of the strings start (relative to start of file, the default), current (relative to the current access position), or end (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

floor arg

Return the value of expression arg rounded down to the nearest integer.

fmod

fmod x y

Return the remainder after dividing expression x by expression y.

for_array_keys

for_array_keys var
array_name code

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_file var
filename code

Loop over the file filename, setting var to the line and executing code for each line in the file.

Example

for_file line /etc/passwd {
    echo $line
}

for_recursive_glob

for_recursive_glob var
dirlist globlist
code

Perform a foreach >-style loop over files that match patterns. All directories in the list dirlist are recursively searched for files that match the glob patterns in list globlist. For each matching file the variable var is set to the file path and code code is 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

fstat fileId
[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 > arrayvar is specified, the information is written into array arrayvar using the listed keys. If only a file identifier is specified, the data is returned as a keyed list.

The following keys are used:

atime

Time of last access.

ctime

Time of last file status change.

dev

Device containing a directory for the file.

gid

Group ID of the file's group.

ino

Inode number.

mode

Mode of the file.

mtime

Time of last file modification.

nlink

Number of links to the file.

size

Size of file in bytes.

tty

1 if the file is associated with a terminal, otherwise 0.

type

Type of the file, which can be file, directory, characterSpecial, blockSpecial, fifo, link, or socket.

uid

User ID of the file's owner.

The following additional keys may be specified, but are not returned with the array or keyed list forms:

remotehost

If fileId is 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.

localhost

If fileId is 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] file
newsize

Truncate a file to a length of at most newsize bytes. With the -fileId option, the file argument is an open file identifier rather than a filename. The -fileId option is not available on Windows.

funlock

funlock fileId
[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 offset start for a length of length bytes. The default start position is the start of file, and the default length is to the end of file.

The value of origin indicates the offset for the locked data and is one of the strings start (relative to start of file, the default), current (relative to the current access position), or end (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 > subject

Display all help pages and lower-level subjects (if any) under the subject subject.

help > subject/helppage

Display 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_info option host

Return information about a network host. The command takes one of the following three forms:

host_info addresses > host

Return a list of the IP addresses for host.

host_info official_name > host

Return the official name for host.

host_info aliases > host

Return a list of aliases for host.

hypot

hypot x y

Return the hypotenuse function, equivalent to sqrt >(x*x + y*y). The arguments are expressions.

id

id options

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.

id user > [name]

Without a name option, return the current username. With an option, sets the real and effective user to name.

id userid > [uid]

Without a uid option, return the current numeric user ID. With an option, set the real and effective user to uid.

id convert userid > uid

Return the username corresponding to numeric user ID uid.

id convert user > name

Return the numeric user ID corresponding to user name.

id group > [name]

Without a name option, return the current group ID name. With an option, set the real and effective group ID to name.

id groupid > [gid]

Without a gid option, return the current numeric group ID. With an option, set the real and effective group ID to gid.

id groups >

Return a list of group names for the current process.

id groupids >

Return a list of numeric group IDs for the current process.

id convert groupid > gid

Return the group name corresponding to numeric group ID gid.

id convert group > name

Return the numeric group ID corresponding to group name.

id effective user >

Return the effective username.

id effective userid >

Return the effective user ID number.

id effective group >

Return the effective group name.

id effective groupid >

Return the effective group ID number.

id host >

Return the hostname of the system on which the program is running.

id process >

Return the process ID of the current process.

id process parent >

Return the process ID of the parent of the current process.

id process group >

Return the process group ID of the current process.

id process group set >

Set the process group ID of the current process to its process ID.

infox

infox option

Return information about the Extended Tcl interpreter or current application. The command can take the following forms:

infox version >

Return the Extended Tcl version number.

infox patchlevel >

Return the Extended Tcl patch level.

infox have_fchown >

Return 1 if the fchown > system call is available otherwise. If available, the -fileId > option on the chown > and chgrp > commands is supported.

infox have_fchmod >

Return 1 if the fchmod > system call is available otherwise. If available, the -fileId > option on the chmod > command is supported.

infox have_flock >

Return 1 if the flock > command is defined, 0 if it is not available.

infox have_fsync >

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.

infox have_ftruncate >

Return 1 if the ftruncate > or chsize > system call is available. If it is, the ftruncate > command -fileId > option may be used.

infox have_msgcats >

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.

infox have_posix_signals >

Return 1 if POSIX signals (block > and unblock > options for the signal > command) are available.

infox have_truncate >

Return 1 if the truncate > system call is available. If it is, the ftruncate > command may truncate by file path.

infox have_waitpid >

Return 1 if the waitpid > system call is available and the wait > command has full functionality, 0 if the wait > command has limited functionality.

infox appname >

Return the symbolic name of the current application linked with the Extended Tcl library. The C variable tclAppName must be set by the application to return an application-specific value for this variable.

infox applongname >

Return a natural language name for the current application. The C variable tclLongAppName must be set by the application to return an application-specific value for this variable.

infox appversion >

Return the version number for the current application. The C variable tclAppVersion must be set by the application to return an application-specific value for this variable.

infox apppatchlevel >

Return the patch level for the current application. The C variable tclAppPatchlevel must be set by the application to return an application-specific value for this variable.

int

int arg

Evaluate the expression arg, convert the result to an integer, and return the converted value.

>

intersect

intersect list1 list2

Return the logical intersection of two lists, i.e., a list of all elements contained in both list1 and list2. The returned list is sorted alphabetically.

intersect3

intersect3 list1 list2

Return a list containing three lists. The first consists of all elements of list1 that are not in list2. The second contains the intersection of the two lists. The third contains all elements of list2 that are not in list1. The returned lists are sorted alphabetically.

keyldel

keyldel listvar key

Delete the field specified by key from the keyed list in variable listvar. Removes both the key and the value from the keyed list.

keylget

keylget listvar
[key]
[retvar|{}]

Return the value associated with key from the keyed list in variable listvar. If retvar is not specified, 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, the value is returned in the variable retvar and the command returns 1 if the key was present within the list. If key is not 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 programmer to determine if a key is present in a keyed list without setting a variable as a side effect.

If key is omitted, a list of all the keys in the keyed list is returned.

keylkeys

keylkeys listvar
[key]

Return a list of the keys in the keyed list contained in variable listvar. If key is specified, it is used as the name of a key field whose subfield keys are to be retrieved.

keylset

keylset listvar
key value...

Set the value associated with key to value in the keyed list contained in variable listvar. If listvar does not exist, it is created. If key is not currently in the list, it is added. If it already exists, value replaces 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. Parameter signal, if present, is the signal number or symbolic name of the signal. The default is 15 (SIGTERM).

If -pgroup > is specified, the numbers in idlist are 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

lassign list
var...

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

lcontain list
element

Return 1 if element is an element of list list; otherwise, return 0.

lempty

lempty list

Return 1 if list is an empty list; otherwise, return 0.

lgets

lgets fileId
[varName]

Read a Tcl list from the file given by file identifier fileId, discarding the terminating newline. If varName is specified, the command writes the list to the variable and returns the number of characters read; otherwise, it returns the list.

link

link [-sym] srcpath
destpath

Create a link from existing pathname srcpath to destpath. With option -sym >, creates a symbolic rather than hard link. This command is not supported under Windows.

lmatch

lmatch [mode]
list pattern

Return a new list, consisting of the elements of list that match pattern. The type of pattern matching is determined by the mode parameter:

-exact

Exact match

-glob

Glob-style matching (default)

-regexp

Regular expression matching

loadlibindex

loadlibindex libfile.tlib

Load the package library index of the library file libfile.tlib.

log

log arg

Return the natural logarithm of expression arg.

log10

log10 arg

Return the base 10 logarithm of expression arg.

loop

loop var first
limit
[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 to first. In each iteration of the loop, if the index is not equal to limit, the command body is evaluated and the index is increased by the value increment.

Example

# count from ten down to one
loop i 10 0 -1 {
    echo $i
}

lrmdups

lrmdups list

Remove duplicate elements from list; return the result, sorted alphabetically.

lvarcat

lvarcat var string...

Concatenate one or more string arguments to the end of the list contained in variable var, storing the result in var and returning the resulting list. String arguments that are lists are deconstructed into individual elements before being concatenated into the result list.

lvarpop

lvarpop var
[indexExpr]
[string]

Remove the element of the list contained in var having index indexExpr (default 0). If string is given, the deleted element is replaced with the string. Returns the replaced or deleted item.

Indices start at 0, and the words end and len can be used at the beginning of the expression to indicate the index of the last element and length of the list, respectively.

lvarpush

lvarpush var
string
[indexExpr]

Insert string as an element of the list stored in var before position indexExpr (default 0).

Indices start at 0, and the words end and len can 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

max number...

Return the argument having the highest numeric value. The arguments can be any mixture of integer or floating-point values.

min

min number...

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 priorityIncr to 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_r
fileId_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

pow x y

Return the value of expression x raised to the power of expression y.

a>

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.

profile off > arrayVar

Turn off profiling and store the results in variable arrayVar for later analysis by the profrep command.

profrep
profrep
> profDataVar
sortKey
[outFile]
[userTitle]

Generate a report using profile data generated by the profile command. Data must have been previously stored in variable profDataVar. The parameter sortKey has one of the values calls, cpu, or real, indicating how to sort the output. The output can optionally be written to file outFile (default is standard out) using an optional title userTitle.

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

random limit

Return a pseudorandom integer greater than or equal to 0 and less than limit.

random seed > [seedval]

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 fileName and return it as a string. The -nonewline > option discards any final newline character in the file. The numBytes option 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_glob dirlist
globlist

Recursively search the directories in list dirlist for files that match any of the patterns in globlist. Returns a list of matching files.

replicate

replicate string
countExpr

Return string replicated the number of times indicated by integer expression countExpr.

round

round arg

Evaluate the expression arg, convert the result to an integer by rounding, and return the converted value.

saveprocs

saveprocs fileName [proc...]

Save the definitions of the listed Tcl procedures (by default, all procedures) to file fileName.

scancontext

scancontext [option]

Create, delete, or modify file scan contexts.

scancontext create >

Create a new scan context.

scancontext delete > contexthandle

Delete the scan context identified by contexthandle.

scancontext copyfile > contexthandle

Return 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.

a name="scanfile">

scanfile

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, 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 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. With option -nocase >, the pattern matching is case insensitive.

searchpath

searchpath pathList
file

Search the directories in list pathList for file file. Return the full path if found; otherwise, return an empty string.

select

select readfileIds
[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 timeout indicates 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

signal action
siglist
[command]

Set the action to take when a Unix signal is received. The siglist parameter lists one or more signal names or numbers. Parameter action indicates 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 command parameter.

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

sin arg

Return the sine of expression arg.

sinh

sinh arg

Return the hyperbolic sine of expression arg.

sleep

sleepseconds

Delay execution of the current process for seconds seconds, which must be an integer value.

sqrt

sqrt arg

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 fileId corresponding to a file open for writing, schedule output for that file to disk. On platforms that do not support the fsync > system call, the fileId parameter is ignored.

system

system cmdstring...

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

tan arg

Return the tangent of expression arg.

tanh

tanh arg

Return the hyperbolic tangent of expression arg.

tclx_errorHandler

tclx_errorHandler message

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 utime stime cutime cstime.

translit

translit inrange
outrange string

Transliterate characters in string, replacing the characters occurring in inrange to the corresponding characters in outrange. The ranges may be lists of characters or a range in the form lower-upper.

Example

translit a-z A-Z "A string"

try_eval

try_eval code
catch [finally]

Evaluate the command string code. If an error occurs, evaluate code and return the result. Last, execute the command string finally.

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

union list1 list2

Return the logical union of two lists, i.e., a list of all elements contained in either list1 or list2. 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 pid to terminate (or any process if pid is 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_file fileName
string...

Write one or more strings to the file named fileName. Each string is terminated with a newline character.


oreilly.com Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies | Privacy Policy

© 2001, O'Reilly & Associates, Inc.