[ Team LiB ]
•
Table of Contents
•
Index
•
Examples
Practical Programming in Tcl and Tk, Fourth Edition By Brent B. Welch , Ken Jones, Jeffrey Hobbs
Publisher: Prentice Hall PTR Pub Date: June 10, 2003 ISBN: 0-13-038560-3 Pages: 960
Practical Programming in Tcl/Tk is described as the "bible" for Tcl programmers. It is a guide to the Tcl/Tk programming language and GUI toolkit. This revision includes substantial updates to cover the new version 8.4-giving both an overview of the features, as well as details about every command in the language. The third edition, written on version 8.2, sold over 30,000 copies. Version 8.4 of Tcl - Tool Command Language-provides substantial updates to one of the most popular UNIX scripting languages. The latest release, includes the addition of a virtual filesystem (VFS), many additional programming widgets (spinbox, panedwindow, labelframe),and improved performance of about 20% over 8.3. The book provides a guide to the best ways to use the tooklit. It not only gives accurate details, but includes extensive examples that demonstrate the best way to use the toolkit. The authors are experts that have both developed the technology and used it to solve problems, so they have many valuable insights to relate to the readers. [ Team LiB ]
[ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE •
Table of Contents
•
Index
•
Examples
Practical Programming in Tcl and Tk, Fourth Edition By Brent B. Welch , Ken Jones, Jeffrey Hobbs
Publisher: Prentice Hall PTR Pub Date: June 10, 2003 ISBN: 0-13-038560-3 Pages: 960
Copyright List of Examples List of Tables Preface Why Tcl? Tcl and Tk Versions Extending Tcl and Tk Tcl on the World Wide Web Ftp Archives Newsgroups Who Should Read This Book How to Read This Book On-line Examples Typographic Conventions Hot Tips Book Organization What's New in the Fourth Edition Other Tcl Books First Edition Thanks Second Edition Thanks Third Edition Thanks Fourth Edition Thanks Contact the Author
Part I. Tcl Basics Chapter 1. Tcl Fundamentals Tcl Commands Hello, World! Variables Command Substitution Math Expressions Backslash Substitution Grouping with Braces and Double Quotes Procedures A Factorial Example More about Variables More about Math Expressions Comments Substitution and Grouping Summary Fine Points Reference Chapter 2. Getting Started The
source
Command
UNIX Tcl Scripts Windows Start Menu Macintosh OS 8/9 and ResEdit The
console
Command
Command-Line Arguments Predefined Variables Chapter 3. The Guestbook CGI Application A Quick Introduction to HTML CGI for Dynamic Pages The
guestbook.cgi Script
Defining Forms and Processing Form Data Handling Errors in CGI Scripts Next Steps Chapter 4. String Processing in Tcl
string Command The append Command The format Command The scan Command The binary Command The
Related Chapters Chapter 5. Tcl Lists Tcl Lists Constructing Lists
llength , lindex, and lrange linsert and lreplace Searching Lists: lsearch Sorting Lists: lsort Getting List Elements: Modifying Lists:
The The
split Command join Command
Related Chapters Chapter 6. Control Structure Commands
If Then Else Switch UNREGISTEREDWhile VERSION OF CHM Foreach For Break and Continue Catch UNREGISTEREDError VERSION OF CHM Return
TO PDF CONVERTER By THETA-SOFTWARE
TO PDF CONVERTER By THETA-SOFTWARE
Chapter 7. Procedures and Scope The
proc Command
Changing Command Names with
rename
Scope The
global
Command
Call by Name Using
upvar upvar
Variable Aliases with Chapter 8. Tcl Arrays Array Syntax The
array
Command
Building Data Structures with Arrays Chapter 9. Working with Files and Programs Running Programs with The
exec
file Command
Cross-Platform File Naming Manipulating Files and Directories File Attributes Input/Output Command Summary Opening Files for I/O Reading and Writing
cd and pwd with glob
The Current Directory Matching File Names The
exit and pid Commands
Environment Variables The
registry Command
Part II. Advanced Tcl Chapter 10. Quoting Issues and Eval
list Command concat inside eval The uplevel Command The subst Command Constructing Code with the Exploiting the
Chapter 11. Regular Expressions When to Use Regular Expressions Regular Expression Syntax Advanced Regular Expressions Syntax Summary The The
regexp regsub
Command Command
Transforming Data to Program with
regsub
Other Commands That Use Regular Expressions Chapter 12. Script Libraries and Packages Locating Packages: The
auto_path Variable
Using Packages Summary of Package Loading The
package
Command
Libraries Based on the The
unknown
tclIndex File
Command
Interactive Conveniences Tcl Shell Library Environment Coding Style Chapter 13. Reflection and Debugging
clock Command The info Command The
Cross-Platform Support Tracing Variables and Commands Interactive Command History Debugging Tcl Dev Kit Other Tools Performance Tuning Chapter 14. Namespaces Using Namespaces Namespace Variables Command Lookup Nested Namespaces Importing and Exporting Procedures Callbacks and Namespaces Introspection The
namespace Command
Converting Existing Packages to use Namespaces
[incr Tcl] Object System xotcl Object System Notes Chapter 15. Internationalization Character Sets and Encodings Message Catalogs
Chapter 16. Event-Driven Programming The Tcl Event Loop
after Command fileevent Command The vwait Command The fconfigure Command The The
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Chapter 17. Socket Programming Networking Extensions for Tcl Client Sockets Server Sockets The Echo Service a URL with UNREGISTEREDFetching VERSION OF HTTP CHM TO PDF CONVERTER By THETA-SOFTWARE The
http Package
Basic Authentication Chapter 18. TclHttpd Web Server Integrating TclHttpd with Your Application Domain Handlers Application Direct URLs Document Types HTML + Tcl Templates Form Handlers Programming Reference Standard Application Direct URLs The TclHttpd Distribution Server Configuration Chapter 19. Multiple Interpreters and Safe-Tcl The
interp
Command
Creating Interpreters Safe Interpreters Command Aliases Hidden Commands Substitutions I/O from Safe Interpreters The Safe Base Security Policies Chapter 20. Safe-Tk and the Browser Plugin Tk in Child Interpreters The Browser Plugin Security Policies and Browser Plugin Configuring Security Policies Chapter 21. Multi-Threaded Tcl Scripts What are Threads? Thread Support in Tcl Getting Started with the Thread Extension Sending Messages to Threads
Preserving and Releasing Threads Error Handling Shared Resources Managing I/O Channels Shared Variables Mutexes and Condition Variables Thread Pools The
Thread
Package Commands
Chapter 22. Tclkit and Starkits Getting Started with Tclkit Virtual File Systems Using sdx to Bundle Applications Exploring the Virtual File System in a Starkit Creating
tclhttpd.kit
Creating a Shared Starkit Metakit More Ideas
Part III. Tk Basics Chapter 23. Tk Fundamentals Hello, World! in Tk Naming Tk Widgets Configuring Tk Widgets Tk Widget Attributes and the Resource Database Summary of the Tk Commands Other Widget Sets Chapter 24. Tk by Example ExecLog The Example Browser A Tcl Shell Chapter 25. The Pack Geometry Manager Packing toward a Side Horizontal and Vertical Stacking The Cavity Model Packing Space and Display Space Resizing and
-expand
Anchoring Packing Order Choosing the Parent for Packing Unpacking a Widget Packer Summary Window Stacking Order Chapter 26. The Grid Geometry Manager A Basic Grid Spanning Rows and Columns
Row and Column Constraints The
grid Command
Chapter 27. The Place Geometry Manager
place
Basics
The Pane Manager The
place
Command
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Chapter 28. The Panedwindow Widget Using the Panedwindow Programming Panedwindow Widgets Panedwindow Attributes
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Chapter 29. Binding Commands to Events The The
bind Command bindtags Command
Event Syntax Modifiers Event Sequences Virtual Events Generating Events Event Summary
Part IV. Tk Widgets Chapter 30. Buttons and Menus Button Commands and Scope Issues Buttons Associated with Tcl Variables Button Attributes Button Operations Menus and Menubuttons Menu Bindings and Events Manipulating Menus and Menu Entries Menu Attributes A Menu by Name Package Chapter 31. The Resource Database An Introduction to Resources Loading Option Database Files Adding Individual Database Entries Accessing the Database User-Defined Buttons User-Defined Menus Chapter 32. Simple Tk Widgets Frames, Labelframes, and Toplevel Windows The Label Widget The Message Widget The Scale Widget The
bell Command
Chapter 33. Scrollbars Using Scrollbars The Scrollbar Protocol The Scrollbar Widget Chapter 34. The Entry and Spinbox Widgets Using Entry Widgets Using Spinbox Widgets Entry and Spinbox Bindings Entry and Spinbox Attributes Programming Entry and Spinbox Widgets Chapter 35. The Listbox Widget Using Listboxes The Listbox Widget Listbox Bindings and Events Listbox Attributes Chapter 36. The Text Widget Text Indices Text Marks Text Tags The Selection Tag Bindings Searching Text Embedded Widgets Embedded Images Looking inside the Text Widget The Undo Mechanism Text Bindings and Events Text Operations Text Attributes Chapter 37. The Canvas Widget Canvas Coordinates Hello, World! The Min Max Scale Example Canvas Objects Canvas Operations Generating Postscript Canvas Attributes Hints
Part V. Tk Details Chapter 38. Selections and the Clipboard> The Selection Model
selection Command The clipboard Command The
Selection Handlers
Chapter 39. Focus, Grabs, and Dialogs Standard Dialogs Custom Dialogs Animation with the
update
Command
Chapter 40. Tk Widget Attributes Configuring Attributes
UNREGISTEREDSize VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Borders and Relief The Focus Highlight Padding and Anchors Chapter 41. Color,OF Images, andTO Cursors UNREGISTERED VERSION CHM PDF CONVERTER By THETA-SOFTWARE Colors Colormaps and Visuals Bitmaps and Images The Text Insert Cursor The Mouse Cursor Chapter 42. Fonts and Text Attributes Naming a Font X Font Names Font Metrics The
font Command
Text Attributes Gridding, Resizing, and Geometry A Font Selection Application Chapter 43. Send The
send Command
The Sender Script Communicating Processes Remote
eval through Sockets
Chapter 44. Window Managers and Window Information
wm Command The winfo Command The tk Command The
Chapter 45. Managing User Preferences App-Defaults Files Defining Preferences The Preferences User Interface Managing the Preferences File Tracing Changes to Preference Variables Improving the Package Chapter 46. A User Interface to Bindings A Pair of Listboxes Working Together The Editing Interface Saving and Loading Bindings
Part VI. C Programming Chapter 47. C Programming and Tcl Basic Concepts Creating a Loadable Package A C Command Procedure
blob Command Example CONST in the Tcl 8.4 APIs The
Strings and Internationalization
Tcl_Main and Tcl_AppInit The Event Loop Invoking Scripts from C Chapter 48. Compiling Tcl and Extensions Standard Directory Structure Building Tcl from Source Using Stub Libraries Using
autoconf
The Sample Extension Chapter 49. Writing a Tk Widget in C Initializing the Extension The Widget Data Structure The Widget Class Command The Widget Instance Command Configuring and Reconfiguring Attributes Specifying Widget Attributes Displaying the Clock The Window Event Procedure Final Cleanup Chapter 50. C Library Overview An Overview of the Tcl C Library An Overview of the Tk C Library
Part VII. Changes Chapter 51. Tcl 7.4/Tk 4.0 wish Obsolete Features The
cget Operation
Input Focus Highlight Bindings Scrollbar Interface
pack info Focus The
send Command
Internal Button Padding Radiobutton Value Entry Widget
Menus Listboxes No
geometry Attribute
Text Widget Color Attributes
tk colormodel scrollincrement
Color Allocation and Canvas
UNREGISTEREDThe VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Selection The
bell Command
Chapter 52. Tcl 7.5/Tk 4.1 Cross-Platform Scripts
clock Command UNREGISTEREDThe VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE load Command The package Command Multiple foreach loop variables The
Event Loop Moves from Tk to Tcl Network Sockets Multiple Interpreters and Safe-Tcl The
grid Geometry
Manager
The Text Widget The Entry Widget Chapter 53. Tcl 7.6/Tk 4.2 More
file Operations
Virtual Events Standard Dialogs
grid Geometry Manager Macintosh unsupported1 Command New
Chapter 54. Tcl/Tk 8.0 The Tcl Compiler Namespaces Safe-Tcl
lsort tcl_precision Variable New
Year 2000 Convention Http Package Serial Line I/O Platform-Independent Fonts The
tk scaling
Command
Application Embedding Native Menus and Menubars CDE Border Width Native Buttons and Scrollbars Images in Text Widgets
destroy grid rowconfigure No Errors from
The Patch Releases
Chapter 55. Tcl/Tk 8.1 Unicode and Internationalization Thread Safety Advanced Regular Expressions New String Commands The DDE Extension Miscellaneous Chapter 56. Tcl/Tk 8.2 The Trf Patch Faster String Operations Empty Array Names Browser Plugin Compatibility Finer Control of Windows Serial Port Monitoring Regular Expression Expanded Syntax Option Chapter 57. Tcl/Tk 8.3 New File Manipulation Commands and Options New
glob Options
Regular Expression Command Enhancements Direct Return of
scan Matches
Removing Duplicate List Elements with
lsort
Deleting Elements from an Array Enhanced
clock
Features
Support for Delayed Package Loading in
pkg_mkIndex
The Img Patch The Dash Patch Other New Tk Features The Patch Releases Chapter 58. Tcl/Tk 8.4 64-Bit Support Additional Filesystem Features and Commands New and Enhanced List Commands Array Searching and Statistics Enhanced Support for Serial Communications New String Comparison Operators Command Tracing Additional Introspection Commands Other Tcl Changes New Tk Widgets Text Widget Undo Mechanism and Other Enhancements New
pack and grid Features
Displaying Both Text and an Image in a Widget New Button Relief Attributes Controlling the State of Entries and Listboxes More Window Manager Interaction Other Tk Changes Chapter 59. About The CD-ROM
Technical Support
Index
[ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
Copyright Library of Congress Cataloging-in-Publication available Editorial/production supervision: Kathleen M. Caren Executive Editor: Mark Taub Editorial Assistant: Noreen Regina Marketing Manager: Kate Hargett Manufacturing Manager: Maura Zaldivar Cover Design Director: Jerry Votta © 2003 Pearson Education Inc. Publishing as Prentice Hall PTR Upper Saddle River, NJ 07458 Prentice Hall books are widely used by corporations and government agencies for training, marketing, and resale. For information regarding corporate and government bulk discounts, contact: Corporate and Government Sales: (800) 382-3419 or
[email protected] All products mentioned herein are trademarks or registered trademarks of their respective owners. All rights reserved. No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 Pearson Education LTD. Pearson Education Australia PTY, Limited Pearson Education Singapore, Pte. Ltd. Pearson Education North Asia Ltd. Pearson Education Canada, Ltd. Pearson Educación de Mexico, S.A. de C.V. Pearson Education-Japan Pearson Education Malaysia, Pte. Ltd.
Dedication to
Jody, Christopher, Daniel, and Michael -Brent Dean, for his support and patience -Ken
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE [ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
List of Examples 1. Tcl Fundamentals 1.1 The "Hello, World!" example 1.2 Tcl variables 1.3 Command substitution 1.4 Simple arithmetic 1.5 Nested commands 1.6 Built-in math functions 1.7 Grouping expressions with braces 1.8 Quoting special characters with backslash 1.9 Continuing long lines with backslashes 1.10 Grouping with double quotes vs. braces 1.11 Embedded command and variable substitution 1.12 Defining a procedure 1.13 A while loop to compute factorial 1.14 A recursive definition of factorial 1.15 Using set to return a variable value 1.16 Embedded variable references 1.17 Using info to determine if a variable exists 1.18 Controlling precision with tcl_precision 2. Getting Started 2.1 A standalone Tcl script on UNIX 2.2 A standalone Tk script on UNIX 2.3 Using /bin/sh to run a Tcl script 2.4 The EchoArgs script 3. The Guestbook CGI Application 3.1 A simple CGI script
3.2 Output of Example 3-1 3.3 The guestbook.cgi script, version 1 3.4 The Cgi_Header procedure 3.5 The guestbook.cgi script, version 2
UNREGISTERED VERSION OF CHM TO PDF CONVERTER 3.6 Initial output of guestbook.cgi with no dataBy THETA-SOFTWARE 3.7 Output of guestbook.cgi with guestbook data 3.8 The newguest.html form 3.9 The newguest.cgi script UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 3.10 The newguest.cgi script with error handling 4. String Processing in Tcl 4.1 Comparing strings with string compare 4.2 Comparing strings with string equal 4.3 Comparing strings with eq 4.4 Mapping Microsoft World special characters to ASCII 5. Tcl Lists 5.1 Constructing a list with the list command 5.2 Using lappend to add elements to a list 5.3 Using lset to set an element of a list 5.4 Using concat to splice lists together 5.5 Double quotes compared to the concat and list commands 5.6 Modifying lists with lreplace 5.7 Deleting a list element by value 5.8 Sorting a list using a comparison function 5.9 Use split to turn input data into Tcl lists 5.10 Implementing join in Tcl 6. Control Structure Commands 6.1 A conditional if then else command 6.2 Chained conditional with elseif 6.3 Using switch for an exact match 6.4 Using switch with substitutions in the patterns
6.5 A switch with "fall through" cases 6.6 Comments in switch commands 6.7 A while loop to read standard input 6.8 Looping with foreach 6.9 Parsing command-line arguments 6.10 Using list with foreach 6.11 Multiple loop variables with foreach 6.12 Multiple value lists with foreach 6.13 A for loop 6.14 A standard catch phrase 6.15 A longer catch phrase 6.16 There are several possible return values from catch 6.17 Raising an error 6.18 Preserving errorInfo when calling error 6.19 Raising an error with return 7. Procedures and Scope 7.1 Default parameter values 7.2 Variable number of arguments 7.3 Variable scope and Tcl procedures 7.4 A random number generator 7.5 Print variable by name 7.6 Improved incr procedure 8. Tcl Arrays 8.1 Using arrays 8.2 Referencing an array indirectly 8.3 Referencing an array indirectly using upvar 8.4 ArrayInvert inverts an array 8.5 Using arrays for records, version 1 8.6 Using arrays for records, version 2 8.7 Using arrays for records, version 3
8.8 Using a list to implement a stack 8.9 Using an array to implement a stack 8.10 A list of arrays 8.11 A list of arrays
UNREGISTERED VERSION OFin-memory CHM TO PDF CONVERTER By THETA-SOFTWARE 8.12 A simple database 9. Working with Files and Programs 9.1 Using exec on a process pipeline 9.2 Comparing modify timesCONVERTER By THETA-SOFTWARE UNREGISTERED VERSION OF file CHM TO PDF 9.3 Determining whether pathnames reference the same file 9.4 Opening a file for writing 9.5 A more careful use of open 9.6 Opening a process pipeline 9.7 Prompting for input 9.8 A read loop using gets 9.9 A read loop using read and split 9.10 Copy a file and translate to native format 9.11 Finding a file by name 9.12 Printing environment variable values 10. Quoting Issues and Eval 10.1 Using list to construct commands 10.2 Generating procedures dynamically with a template 10.3 Using eval with $args 10.4 lassign: list assignment with foreach 10.5 The File_Process procedure iterates over lines in a file 11. Regular Expressions 11.1 Expanded regular expressions allow comments 11.2 Using regular expressions to parse a string 11.3 A pattern to match URLs 11.4 An advanced regular expression to match URLs 11.5 The Url_Decode procedure
11.6 The Cgi_List and Cgi_Query procedures 11.7 Cgi_Parse and Cgi_Value store query data in the cgi array 11.8 Html_DecodeEntity 11.9 Html_Parse 12. Script Libraries and Packages 12.1 Maintaining a tclIndex file 12.2 Loading a tclIndex file 13. Reflection and Debugging 13.1 Calculating clicks per second 13.2 Printing a procedure definition 13.3 Mapping form data onto procedure arguments 13.4 Finding built-in commands 13.5 Getting a trace of the Tcl call stack 13.6 A procedure to read and evaluate commands 13.7 Using info script to find related files 13.8 Tracing variables 13.9 Creating array elements with array traces 13.10 Interactive history usage 13.11 Implementing special history syntax 13.12 A Debug procedure 13.13 Time Stamps in log records 14. Namespaces 14.1 Random number generator using namespaces 14.2 Random number generator using qualified names 14.3 Nested namespaces 14.4 The code procedure to wrap callbacks 14.5 Listing commands defined by a namespace 15. Internationalization 15.1 MIME character sets and file encodings 15.2 Using scripts in nonstandard encodings
15.3 Three sample message catalog files 15.4 Using msgcat::mcunknown to share message catalogs 16. Event-Driven Programming 16.1 A read event file handler
UNREGISTERED VERSION OF CHM TO PDF By THETA-SOFTWARE 16.2 Using vwait to activate theCONVERTER event loop 16.3 A read event file handler for a nonblocking channel 17. Socket Programming 17.1 Opening client TO socket with a timeout UNREGISTERED VERSION OFa CHM PDF CONVERTER By THETA-SOFTWARE 17.2 Opening a server socket 17.3 The echo service 17.4 A client of the echo service 17.5 Opening a connection to an HTTP server 17.6 Opening a connection through a HTTP proxy 17.7 Http_Head validates a URL 17.8 Using Http_Head 17.9 Http_Get fetches the contents of a URL" endterm="ch17list09.title"/> 17.10 HttpGetText reads text URLs 17.11 HttpCopyDone is used with fcopy 17.12 Downloading files with http::geturl 17.13 Basic Authentication using http::geturl 18. TclHttpd Web Server 18.1 The hello.tcl file implements /hello/world 18.2 A simple URL domain 18.3 Application Direct URLs 18.4 Alternate types for Application Direct URLs 18.5 A sample document type handler 18.6 A one-level site structure 18.7 A two-level site structure 18.8 A HTML + Tcl template file 18.9 SitePage template procedure, version 1
18.10 SiteMenu and SiteFooter template procedures 18.11 The SiteLink procedure 18.12 Mail form results with /mail/forminfo 18.13 Mail message sent by /mail/forminfo 18.14 Processing mail sent by /mail/forminfo 18.15 Processing mail sent by /mail/forminfo, Safe-Tcl version 18.16 A self-checking form procedure 18.17 A page with a self-checking form 18.18 Generating a table with html::foreach 18.19 The /debug/source Application Direct URL implementation 19. Multiple Interpreters and Safe-Tcl 19.1 Creating and deleting an interpreter 19.2 Creating a hierarchy of interpreters 19.3 A command alias for exit 19.4 Querying aliases 19.5 Dumping aliases as Tcl commands 19.6 Substitutions and hidden commands 19.7 Opening a file for an unsafe interpreter 19.8 The Safesock security policy 19.9 The Tempfile security policy 19.10 Restricted puts using hidden commands 19.11 A safe after command 20. Safe-Tk and the Browser Plugin 20.1 Using EMBED to insert a Tclet 21. Multi-Threaded Tcl Scripts 21.1 Creating a separate thread to perform a lengthy operation 21.2 Initializing a thread before entering its event loop 21.3 Creating several threads in an application 21.4 Using joinable threads to detect thread termination 21.5 Examples of synchronous message sending
21.6 Using a return variable with synchronous message sending 21.7 Executing commands after thread::wait returns 21.8 Creating a custom thread error handler 21.9 A basic implementation of a logging thread
UNREGISTERED VERSION OF CHM PDF CONVERTER By THETA-SOFTWARE 21.10 Deferring socketTO transfer until after the connection callback 21.11 Working around Tcl's socket transfer bug 21.12 A multi-threaded echo server 21.13 UsingOF a mutex a shared resource UNREGISTERED VERSION CHM to TOprotect PDF CONVERTER By THETA-SOFTWARE 21.14 Standard condition variable use for a signalling thread 21.15 Standard condition variable use for a waiting thread 22. Tclkit and Starkits 22.1 Accessing a Zip file through a VFS 22.2 The output of sdx lsk hello.kit 22.3 The main program of a Starkit 22.4 The pkgIndex.tcl in a Starkit 22.5 A Starkit that examines its Virtual File System 22.6 Creating a simple Starkit 22.7 The contents of the tclhttpd.vfs directory, version 1 22.8 The main program for the TclHttpd Starkit, version 1 22.9 Contents of the tclhttpd.vfs directory, version 2 22.10 The main program for the TclHttpd Starkit, version 2 22.11 The Standard Tcl Library Starkit main.tcl file 22.12 The main program for TclHttpd Starkit, version 3 22.13 Examining the views in a Metakit database 22.14 Examining data in a Metakit view 22.15 Selecting data with mk::select 22.16 Creating a new view 22.17 Adding data to a view 22.18 Storing data in a Starkit 23. Tk Fundamentals
23.1 "Hello, World!" Tk program 23.2 Looking at all widget attributes 24. Tk by Example 24.1 Logging the output of a program run with exec 24.2 A platform-specific cancel event 24.3 A browser for the code examples in the book 24.4 A Tcl shell in a text widget 24.5 Macintosh look and feel 24.6 Windows look and feel 24.7 UNIX look and feel 25. The Pack Geometry Manager 25.1 Two frames packed inside the main frame 25.2 Turning off geometry propagation 25.3 A horizontal stack inside a vertical stack 25.4 Even more nesting of horizontal and vertical stacks 25.5 Mixing bottom and right packing sides 25.6 Filling the display into extra packing space 25.7 Using horizontal fill in a menu bar 25.8 The effects of internal padding (-ipady) 25.9 Button padding vs. packer padding 25.10 The look of a default button 25.11 Resizing without the expand option 25.12 Resizing with expand turned on 25.13 More than one expanding widget 25.14 Setup for anchor experiments 25.15 The effects of noncenter anchors 25.16 Animating the packing anchors 25.17 Controlling the packing order 25.18 Packing into other relatives 26. The Grid Geometry Manager
26.1 A basic grid 26.2 A grid with sticky settings 26.3 A grid with row and column specifications 26.4 A grid with external padding
UNREGISTERED VERSION TOpadding PDF CONVERTER By THETA-SOFTWARE 26.5 A grid OF withCHM internal 26.6 All combinations of -sticky settings 26.7 Explicit row and column span 26.8 Grid syntax row and span UNREGISTERED VERSION OF CHM TO column PDF CONVERTER By THETA-SOFTWARE 26.9 Row padding compared to cell padding 26.10 Gridding a text widget and scrollbar 26.11 Uniform column width 27. The Place Geometry Manager 27.1 Centering a window with place 27.2 Covering a window with place 27.3 Combining relative and absolute sizes 27.4 Positioning a window above a sibling with place 27.5 Pane_Create sets up vertical or horizontal panes 27.6 PaneDrag adjusts the percentage 27.7 PaneGeometry updates the layout 28. The Panedwindow Widget 28.1 A panedwindow with complex managed widgets 29. Binding Commands to Events 29.1 Bindings on different binding tags 29.2 Output from the UNIX xmodmap program 29.3 Emacs-like binding convention for Meta and Escape 29.4 Virtual events for cut, copy, and paste 30. Buttons and Menus 30.1 A troublesome button command 30.2 Fixing the troublesome situation 30.3 A button associated with a Tcl procedure
30.4 Radiobuttons and checkbuttons 30.5 A command on a radiobutton or checkbutton 30.6 A menu sampler 30.7 A menu bar in Tk 8.0 30.8 Using the <
> virtual event 30.9 A simple menu by name package 30.10 Using the Tk 8.0 menu bar facility 30.11 MenuGet maps from name to menu 30.12 Adding menu entries 30.13 A wrapper for cascade entries 30.14 Using the menu by name package 30.15 Keeping the accelerator display up to date 31. The Resource Database 31.1 Reading an option database file 31.2 A file containing resource specifications 31.3 Using resources to specify user-defined buttons 31.4 Resource_ButtonFrame defines buttons based on resources 31.5 Using Resource_ButtonFrame 31.6 Specifying menu entries via resources 31.7 Defining menus from resource specifications 31.8 Resource_GetFamily merges user and application resources 32. Simple Tk Widgets 32.1 Labelframe example 32.2 Using the labelAnchor option to position a labelframe's anchor 32.3 Associating an existing label widget with a labelframe 32.4 Macintosh window styles 32.5 A label that displays different strings 32.6 The message widget formats long lines of text 32.7 Controlling the text layout in a message widget 32.8 A scale widget
33. Scrollbars 33.1 A text widget and two scrollbars 33.2 Scroll_Set manages optional scrollbars 33.3 Listbox with optional scrollbars
UNREGISTERED VERSION OF CHM Widgets TO PDF CONVERTER By THETA-SOFTWARE 34. The Entry and Spinbox 34.1 Associating entry widgets with variables and commands 34.2 Restricting entry text to integer values 34.3 Reestablishing an idle taskBy THETA-SOFTWARE UNREGISTERED VERSION OF CHMvalidation TO PDFusing CONVERTER 34.4 A simple spinbox with calculated values 34.5 Formatting numeric values in a spinbox 34.6 Enumerating spinbox values and wrapping 34.7 Using the spinbox readonly state 35. The Listbox Widget 35.1 Using -listvariable to link a listbox and variable 35.2 Choosing items from a listbox 35.3 Using the <> virtual event 36. The Text Widget 36.1 Tag configurations for basic character styles 36.2 Line spacing and justification in the text widget 36.3 An active text button 36.4 Delayed creation of embedded widgets 36.5 Using embedded images for a bulleted list 36.6 Finding the current range of a text tag 36.7 Dumping the text widget 36.8 Dumping the text widget with a command callback 37. The Canvas Widget 37.1 A large scrolling canvas 37.2 The canvas "Hello, World!" example 37.3 A min max scale canvas example 37.4 Moving the markers for the min max scale
37.5 Canvas arc items 37.6 Canvas bitmap items 37.7 Canvas image items 37.8 A canvas stroke drawing example 37.9 Canvas oval items 37.10 Canvas polygon items 37.11 Dragging out a box 37.12 Simple edit bindings for canvas text items 37.13 Using a canvas to scroll a set of widgets 37.14 Generating Postscript from a canvas 38. Selections and the Clipboard 38.1 Paste the PRIMARY or CLIPBOARD selection 38.2 Separate paste actions 38.3 Bindings for canvas selection 38.4 Selecting objects 38.5 A canvas selection handler 38.6 The copy and cut operations 38.7 Pasting onto the canvas 39. Focus, Grabs, and Dialogs 39.1 Procedures to help build dialogs 39.2 A simple dialog 39.3 A feedback procedure 40. Tk Widget Attributes 40.1 Equal-sized labels 40.2 3D relief sampler 40.3 Padding provided by labels and buttons 40.4 Anchoring text in a label or button 40.5 Borders and padding 41. Color, Images, and Cursors 41.1 Resources for reverse video
41.2 Computing a darker color 41.3 Specifying an image for a widget 41.4 Specifying a bitmap for a widget 41.5 The built-in bitmaps
UNREGISTERED VERSION CHM TO PDF CONVERTER By THETA-SOFTWARE 41.6 The TkOF cursors 42. Fonts and Text Attributes 42.1 The FontWidget procedure handles missing fonts 42.2 Font metrics UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 42.3 A gridded, resizable listbox 42.4 Font selection dialog 43. Send 43.1 The sender application 43.2 Hooking the browser to an eval server 43.3 Making the shell into an eval server 43.4 Remote eval using sockets 43.5 Reading commands from a socket 43.6 The client side of remote evaluation 44. Window Managers and Window Information 44.1 Gridded geometry for a canvas 44.2 Telling other applications what your name is 45. Managing User Preferences 45.1 Preferences initialization 45.2 Adding preference items 45.3 Setting preference variables 45.4 Using the preferences package 45.5 A user interface to the preference items 45.6 Interface objects for different preference types 45.7 Displaying the help text for an item 45.8 Saving preferences settings to a file 45.9 Read settings from the preferences file
45.10 Tracing a Tcl variable in a preference item 46. A User Interface to Bindings 46.1 A user interface to widget bindings 46.2 Bind_Display presents the bindings for a widget or class 46.3 Related listboxes are configured to select items together 46.4 Controlling a pair of listboxes with one scrollbar 46.5 Drag-scrolling a pair of listboxes together 46.6 An interface to define bindings 46.7 Defining and saving bindings 47. C Programming and Tcl 47.1 The initialization procedure for a loadable package 47.2 The RandomCmd C command procedure 47.3 The RandomObjCmd C command procedure 47.4 The Tcl_Obj structure 47.5 The Plus1ObjCmd procedure 47.6 The Blob and BlobState data structures 47.7 The Blob_Init and BlobCleanup procedures 47.8 The BlobCmd command procedure 47.9 BlobCreate and BlobDelete 47.10 The BlobNames procedure 47.11 \The BlobN and BlobData procedures 47.12 The BlobCommand and BlobPoke procedures 47.13 A canonical Tcl main program and Tcl_AppInit 47.14 A canonical Tk main program and Tk_AppInit 47.15 Calling C command procedure directly with Tcl_Invoke 48. Compiling Tcl and Extensions Writing a Tk Widget in C 49.1 The Clock_Init procedure 49.2 The Clock widget data structure 49.3 The ClockCmd command procedure
49.4 The ClockObjCmd command procedure 49.5 The ClockInstanceCmd command procedure 49.6 The ClockInstanceObjCmd command procedure 49.7 ClockConfigure allocates resources for the widget
UNREGISTERED VERSION OF CHM TO PDF CONVERTER THETA-SOFTWARE 49.8 ClockObjConfigure allocates resources forBy the widget 49.9 The Tk_ConfigSpec typedef 49.10 Configuration specs for the clock widget 49.11 The Tk_OptionSpec typedef UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 49.12 The Tk_OptionSpec structure for the clock widget 49.13 ComputeGeometry computes the widget's size 49.14 The ClockDisplay procedure 49.15 The ClockEventProc handles window events 49.16 The ClockDestroy cleanup procedure 49.17 The ClockObjDelete command 500C Library Overview [ Team LiB ]
[ Team LiB ]
List of Tables 1. Tcl Fundamentals 1-1 Backslash sequences 1-2 Arithmetic operators from highest to lowest precedence 1-3 Built-in math functions 1-4 Built-in Tcl commands 2. Getting Started 2-1 Wish command line options 2-2 Variables defined by tclsh and wish 3. The Guestbook CGI Application 3-1 HTML tags used in the examples 4. String Processing in Tcl 4-1 The string command 4-2 Matching characters used with string match 4-3 Character class names 4-4 Format conversions 4-5 Format flags 4-6 Binary conversion types 5. Tcl Lists 5-1 List-related commands 5-2 Options to the lsearch command 8. Tcl Arrays 8-1 The array command 9. Working with Files and Programs 9-1 Summary of the exec syntax for I/O redirection 9-2 The file command options 9-3 Array elements defined by file stat
9-4 Platform-specific file attributes 9-5 Tcl commands used for file access 9-6 Summary of the open access arguments 9-7 Summary of POSIX flags for the access argument
UNREGISTERED VERSION OF CHMoptions TO PDF CONVERTER By THETA-SOFTWARE 9-8 glob command 9-9 The registry command 9-10 The registry data types 11. Regular Expressions UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 11-1 Additional advanced regular expression syntax 11-2 Backslash escapes in regular expressions 11-3 Character classes 11-4 Embedded option characters used with the (?x) syntax 11-5 Options to the regexp command 11-6 Sample regular expressions 12. Script Libraries and Packages 12-1 Options to the pkg_mkIndex command 12-2 The package command 13. Reflection and Debugging 13-1 clock format keywords 13-2 The clock command 13-3 The info command 13-4 The history command 13-5 Special history syntax 14. Namespaces 14-1 The namespace command 15. Internationalization 15-1 The encoding command 15-2 The msgcat package 16. Event-Driven Programming 16-1 The after command
16-2 The fileevent command 16-3 I/O channel properties controlled by fconfigure 16-4 Serial line properties controlled by fconfigure 16-5 End of line translation modes 17. Socket Programming 17-1 Options to the http::geturl command 17-2 The http support procedures 17-3 Elements of the http::geturl state array 18. TclHttpd Web Server 18-1 Httpd support procedures 18-2 Url support procedures 18-3 Doc procedures for configuration 18-4 Doc procedures for generating responses 18-5 Doc procedures that support template processing 18-6 Elements of the page array 18-7 Elements of the env array 18-8 Status Application Direct URLs 18-9 Debug Application Direct URLs 18-10 Application Direct URLS that email form results 18-11 Basic TclHttpd parameters 19. Multiple Interpreters and Safe-Tcl 19-1 The interp command 19-2 Commands hidden from safe interpreters 19-3 The safe base master interface 19-4 The safe base slave aliases 20. Safe-Tk and the Browser Plugin 20-1 Tk commands omitted from safe interpreters 20-2 Aliases defined by the browser package 20-3 The browser::getURL callbacks 21. Multi-Threaded Tcl Scripts
21-1 The commands of the thread namespace 21-2 Thread configuration options 21-3 The commands of the tsv namespace 21-4 The commands of the tpool namespace
UNREGISTERED VERSION CHM TO PDF options CONVERTER By THETA-SOFTWARE 21-5 ThreadOF pool configuration 22. Tclkit and Starkits 22-1 Return values of the starkit::startup procedure 23. Tk Fundamentals UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 23-1 Tk widget-creation commands 23-2 Tk widget-manipulation commands 23-3 Tk support procedures 25. The Pack Geometry Manager 25-1 The pack command 25-2 Packing options 26. The Grid Geometry Manager 26-1 The grid command 26-2 Grid widget options 27. The Place Geometry Manager 27-1 The place command 27-2 Placement options 28. The Panedwindow Widget 28-1 Panedwindow operations 28-2 Panedwindow attributes 28-3 Panedwindow managed widget options 29. Binding Commands to Events 29-1 Event types 29-2 Event modifiers 29-3 The event command 29-4 A summary of the event keywords 30. Buttons and Menus
30-1 Resource names of attributes for all button widgets 30-2 Button operations 30-3 Menu entry index keywords 30-4 Menu operations 30-5 Menu attribute resource names 30-6 Attributes for menu entries 32. Simple Tk Widgets 32-1 Attributes for frame, labelframe, and toplevel widgets 32-2 Label Attributes 32-3 Message Attributes 32-4 Bindings for scale widgets 32-5 Attributes for scale widgets 32-6 Operations on the scale widget 33. Scrollbars 33-1 Attributes for the scrollbar widget 33-2 Bindings for the scrollbar widget 33-3 Operations on the scrollbar widget 34. The Entry and Spinbox Widgets 34-1 Entry and spinbox validation substitutions 34-2 Entry and spinbox bindings 34-3 Entry and spinbox attribute resource names 34-4 Entry and spinbox indices 34-5 Entry and spinbox operations 35. The Listbox Widget 35-1 Listbox indices 35-2 Listbox operations 35-3 Listbox item configuration options 35-4 The values for the selectMode of a listbox 35-5 Bindings for browse selection mode 35-6 Bindings for single selection mode
35-7 Bindings for extended selection mode 35-8 Bindings for multiple selection mode 35-9 Listbox scroll bindings 35-10 Listbox attribute resource names
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 36. The Text Widget 36-1 Text indices 36-2 Index modifiers for text widgets 36-3 Attributes for text tags UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 36-4 Options to the search operation 36-5 Window and image alignment options 36-6 Options to the window create operation 36-7 Options to the image create operation 36-8 Bindings for the text widget 36-9 Operations for the text widget 36-10 Text attribute resource names 37. The Canvas Widget 37-1 Common canvas item attributes 37-2 Canvas dash pattern characters 37-3 Arc attributes 37-4 Bitmap attributes 37-5 Image attributes 37-6 Line attributes 37-7 Polygon attributes 37-8 Indices for canvas text items 37-9 Canvas operations that apply to text items 37-10 Text attributes 37-11 Window attributes 37-12 Operations on a canvas widget 37-13 Canvas postscript options 37-14 Canvas attribute resource names
38. Selections and the Clipboard 38-1 The selection command 38-2 The clipboard command 39. Focus, Grabs, and Dialogs 39-1 Options to tk_messageBox 39-2 Options to the standard file and directory dialogs 39-3 Options to tk_chooseColor 39-4 The focus command 39-5 The grab command 39-6 he tkwait command 40. Tk Widget Attributes 40-1 Size attribute resource names 40-2 Border and relief attribute resource names 40-3 Highlight attribute resource names 40-4 Layout attribute resource names 41. Color, Images, and Cursors 41-1 Color attribute resource names 41-2 Windows system colors 41-3 Macintosh system colors 41-4 Visual classes for displays 41-5 Summary of the image command 41-6 Bitmap image options 41-7 Photo image attributes 41-8 Photo image operations 41-9 Copy options for photo images 41-10 Read options for photo images 41-11 Write options for photo images 41-12 Cursor attribute resource names 42. Fonts and Text Attributes 42-1 Font attributes
42-2 X Font specification components 42-3 Layout attribute resource names 42-4 The font command 42-5 Selection attribute resource names
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 43. Send 43-1 Options to the send command 44. Window Managers and Window Information 44-1 Size, placement and PDF decoration window manager operations UNREGISTERED VERSION OF CHM TO CONVERTER By THETA-SOFTWARE 44-2 Window manager commands for icons 44-3 Session-related window manager operations 44-4 Miscellaneous window manager operations 44-5 send command information 44-6 Window hierarchy information 44-7 Window location information 44-8 Window size information 44-9 Virtual root window information 44-10 Atom and window ID information 44-11 Colormap and visual class information 44-12 The tk command operations 47. C Programming and Tcl 47-1 Defines to control the meaning of CONST in the Tcl APIs 48. Compiling Tcl and Extensions 48-1 The Tcl source directory structure 48-2 The installation directory structure 48-3 Standard configure flags 48-4 TEA standard Makefile targets 49. Writing a Tk Widget in C 49-1 Configuration flags and corresponding C types 51. Tcl 7.4/Tk 4.0 51-1 Changes in color attribute names
55. Tcl/Tk 8.1 55-1 The testthread command 55-2 The dde command options [ Team LiB ]
[ Team LiB ]
Preface UNREGISTERED OF CHM TO PDFTclCONVERTER By THETA-SOFTWARE Tcl stands VERSION for Tool Command Language. is really two things: a scripting language, and an interpreter for that language that is designed to be easy to embed into your application. Tcl and its associated graphical user-interface toolkit, Tk, were designed and crafted by Professor John Ousterhout of the University of California, Berkeley. You can find these packages on the Internet and use them freely in your application, even if it is commercial. The Tcl interpreter has been ported from UNIX to DOS, PalmOS, VMS, Windows, OS/2, NT, and Macintosh UNREGISTERED VERSION CHM PDF CONVERTER By THETA-SOFTWARE environments. The Tk OF toolkit hasTO been ported from the X window system to Windows and Macintosh. I first heard about Tcl in 1988 while I was Ousterhout's Ph.D. student at Berkeley. We were designing a network operating system, Sprite. While the students hacked on a new kernel, John wrote a new editor and terminal emulator. He used Tcl as the command language for both tools so that users could define menus and otherwise customize those programs. This was in the days of X10, and he had plans for an X toolkit based on Tcl that would help programs cooperate with each other by communicating with Tcl commands. To me, this cooperation among tools was the essence of Tcl. This early vision imagined that applications would be large bodies of compiled code and a small amount of Tcl used for configuration and high-level commands. John's editor, mx, and the terminal emulator, tx, followed this model. While this model remains valid, it has also turned out to be possible to write entire applications in Tcl. This is because the Tcl/Tk shell, wish, provides access to other programs, the file system, network sockets, plus the ability to create a graphical user interface. For better or worse, it is now common to find applications that contain thousands of lines of Tcl script. This book was written because, while I found it enjoyable and productive to use Tcl and Tk, there were times when I was frustrated. In addition, working at Xerox PARC, with many experts in languages and systems, I was compelled to understand both the strengths and weaknesses of Tcl and Tk. Although many of my colleagues adopted Tcl and Tk for their projects, they were also just as quick to point out its flaws. In response, I have built up a set of programming techniques that exploit the power of Tcl and Tk while avoiding troublesome areas. This book is meant as a practical guide to help you get the most out of Tcl and Tk and avoid some of the frustrations I experienced. It has been about 14 years since I was introduced to Tcl, and about eight years since the first edition of this book. During several of those years I worked under John Ousterhout, first at Sun Microsystems and then at Scriptics Corporation. There I remained mostly a Tcl programmer while others in our group have delved into the C implementation of Tcl itself. I've built applications like HTML editors, email user interfaces, Web servers, and the customer database we ran our business on. This experience is reflected in this book. The bulk of the book is about Tcl scripting, and the aspects of C programming to create Tcl extensions is given a lighter treatment. I have been lucky to remain involved in the core Tcl development, and I hope I can pass along the insights I have gained by working with Tcl. [ Team LiB ]
[ Team LiB ]
Why Tcl? As a scripting language, Tcl is similar to other UNIX shell languages such as the Bourne Shell (sh), the C Shell (csh), the Korn Shell (ksh), and Perl. Shell programs let you execute other programs. They provide enough programmability (variables, control flow, and procedures) to let you build complex scripts that assemble existing programs into a new tool tailored for your needs. Shells are wonderful for automating routine chores. It is the ability to easily add a Tcl interpreter to your application that sets it apart from other shells. Tcl fills the role of an extension language that is used to configure and customize applications. There is no need to invent a configuration file format or a command language for your new application, or struggle to provide some sort of user-programmability for your tool. Instead, by adding a Tcl interpreter, you structure your application as a set of primitive operations that can be composed by a script to best suit the needs of your users. It also allows other programs to have programmatic control over your application, leading to suites of applications that work well together. The Tcl C library has clean interfaces and is simple to use. The library implements the basic interpreter and a set of core scripting commands that implement variables, flow control, and procedures (see page 22). There is also a broad set of APIs that access operating system services to run other programs, access the file system, and use network sockets. Tk adds commands to create graphical user interfaces. The Tcl and Tk C APIs provide a "virtual machine" that is portable across UNIX, Windows, and Macintosh environments. The Tcl virtual machine is extensible because your application can define new Tcl commands. These commands are associated with a C or C++ procedure that your application provides. The result is applications that are split into a set of primitives written in a compiled language and exported as Tcl commands. A Tcl script is used to compose the primitives into the overall application. The script layer has access to shell-like capability to run other programs, has access to the file system, and can call directly into the compiled part of the application through the Tcl commands you define. In addition, from the C programming level, you can call Tcl scripts, set and query Tcl variables, and even trace the execution of the Tcl interpreter. There are many Tcl extensions freely available on the Internet. Most extensions include a C library that provides some new functionality, and a Tcl interface to the library. Examples include database access, telephone control, MIDI controller access, and expect, which adds Tcl commands to control interactive programs. The most notable extension is Tk, a toolkit for graphical user interfaces. Tk defines Tcl commands that let you create and manipulate user interface widgets. The script-based approach to user interface programming has three benefits: Development is fast because of the rapid turnaround; there is no waiting for long compilations. The Tcl commands provide a higher-level interface than most standard C library userinterface toolkits. Simple user interfaces require just a handful of commands to define them. At the same time, it is possible to refine the user interface in order to get every detail just so. The fast turnaround aids the refinement process. The user interface can be factored out from the rest of your application. The developer
can concentrate on the implementation of the application core and then fairly painlessly work up a user interface. The core set of Tk widgets is often sufficient for all your user interface needs. However, it is also possible to write custom Tk widgets in C, and again there are many contributed Tk widgets available on the network. There are other choices for extension languages that include Visual Basic, Scheme, Elisp, Perl, Python, Ruby and Javascript. Your choice between them is partly a matter of taste. Tcl has simple constructs and looks somewhat like C. It is easy to add new Tcl primitives by writing C UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE procedures. Tcl is very easy to learn, and I have heard many great stories of users completing impressive projects in a short amount of time (e.g., a few weeks), even though they never used Tcl before. Java has exploded onto the computer scene since this book was first published. Java is a great systems programming language that in the long run could displace C and C++. This is fine for UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Tcl, which is designed to glue together building blocks written in any system programming language. Tcl was designed to work with C, but has been adapted to work with the Java Virtual Machine. Where I say "C or C++", you can now say "C, C++, or Java," but the details are a bit different with Java. This book does not describe the Tcl/Java interface, but you can find TclBlend on the CD-ROM. TclBlend loads the Java Virtual Machine into your Tcl application and lets you invoke Java methods. It also lets you implement Tcl commands in Java instead of C or C++. Jacl is a Tcl interpreter written in Java. It has some limitations compared with the native C-based Tcl interpreter, but Jacl is great if you cannot use the native interpreter. Javascript is a language from Netscape that is designed to script interactions with Web pages. Javascript is important because of its use in HTML user interfaces. However, Tcl provides a more general purpose scripting solution that can be used in a wide variety of applications. The Tcl/Tk Web browser plugin provides a way to run Tcl in your browser. It turns out to be more of a Java alternative than a JavaScript alternative. The plugin lets you run Tcl applications inside your browser, while JavaScript gives you fine grain control over the browser and HTML display. The plugin is described in Chapter 20. [ Team LiB ]
[ Team LiB ]
Tcl and Tk Versions Tcl and Tk continue to evolve. See http://www.beedub.com/book/ for updates and news about the latest Tcl releases. Tcl and Tk have had separate version numbers for historical reasons, but they are released in pairs that work together. The original edition of this book was based on Tcl 7.4 and Tk 4.0, and there were a few references to features in Tk 3.6. This fourth edition has been updated to reflect new features added through Tcl/Tk 8.4: Tcl 7.5 and Tk 4.1 had their final release in May 1996. These releases feature the port of Tk to the Windows and Macintosh environments. The Safe-Tcl security mechanism was introduced to support safe execution of network applets. There is also network socket support and a new Input/Output (I/O) subsystem to support high-performance eventdriven I/O. Tcl 7.6 and Tk 4.2 had their final release in October 1996. These releases include improvements in Safe-Tcl, and improvements to the grid geometry manager introduced in Tk 4.1. Cross-platform support includes virtual events (e.g., <> as opposed to ), standard dialogs, and more file manipulation commands. Tcl 7.7 and Tk 4.3 were internal releases used for the development of the Tcl/Tk plug-in for the Netscape Navigator and Microsoft Internet Explorer Web browsers. Their development actually proceeded in parallel to Tcl 7.6 and Tk 4.2. The plug-in has been released for a wide variety of platforms, including Solaris/SPARC, Solaris/INTEL, SunOS, Linux, Digital UNIX, IRIX, HP/UX, Windows 95, Windows NT, and the Macintosh. The browser plug-in supports Tcl applets in Web pages and uses the sophisticated security mechanism of Safe-Tcl to provide safety. Tcl 8.0 features an on-the-fly compiler for Tcl that provides many-times faster Tcl scripts. Tcl 8.0 supports strings with embedded null characters. The compiler is transparent to Tcl scripts, but extension writers need to learn some new C APIs to take advantage of its potential. The release history of 8.0 spread out over a couple of years as John Ousterhout moved from Sun Microsystems to Scriptics Corporation. The widely used 8.0p2 release was made in the fall of 1997, but the final patch release, 8.0.5, was made in the spring of 1999. Tk changed its version to match Tcl at 8.0. Tk 8.0 includes a new platform-independent font mechanism, native menus and menu bars, and more native widgets for better native look and feel on Windows and Macintosh. Tcl/Tk 8.1 features full Unicode support, a new regular expression engine that provides all the features found in Perl 5, and thread safety so that you can embed Tcl into multi threaded applications. Tk does a heroic job of finding the correct font to display your Unicode characters, and it adds a message catalog facility so that you can write internationalized applications. The release history of Tcl/Tk 8.1 also straddled the Sun to Scriptics transition. The first alpha release was made in the fall of 1997, and the final patch release, 8.1.1, was made in May 1999. Tcl/Tk 8.2 is primarily a bug fix and stabilization release. There are a few minor additions to the Tcl C library APIs to support more extensions without requiring core patches. Tcl/Tk 8.2 went rapidly into final release in the summer of 1999.
Tcl/Tk 8.3 adds a broad collection of enhancements to Tcl and Tk. Tk started to get some long deserved attention with adoption of the Dash and Image patches from Jan Nijtmans. The 8.3.0 release was in February, 2000, and the last patch release, 8.3.5, was made in October, 2002. Tcl/Tk 8.4 features a focus on performance, the addition of the Virtual File System Interface, and 3 new core Tk widgets: spinbox, labeledframe, and panedwindow. This release was a long time in development. The first beta release was in June, 2000, and the UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE 8.4.2 release was made in March, 2003. [ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
Extending Tcl and Tk Tcl is designed so that interesting additions can be made as extensions that do not require changes to the Tcl core. Many extensions are available today: You can find them on the Web at: http://www.tcl.tk/resource/ However, some changes require changes to Tcl/Tk itself. If you are interested in contributing to the continued improvement of Tcl/Tk, you can help. There is a Tcl Core Team (TCT) and a formal Tcl Improvement Process (TIP). You can browse the current TIPs or contribute your own at: http://www.tcl.tk/cgi-bin/tct/tip/ The Tcl and Tk source code is maintained on a SourceForge project: http://www.sourceforge.net/projects/tcl http://www.sourceforge.net/projects/tktoolkit All bug reports and patch submissions are logged in a database. Source code patches that are made according to the Tcl Engineering Manual guidelines have the most chance of adoption. These guidelines describe code appearance (e.g., indentation), test suite requirements, and documentation requirements. [ Team LiB ]
[ Team LiB ]
Tcl on the World Wide Web Start with VERSION these WorldOF Wide WebTO pages about Tcl: UNREGISTERED CHM PDF CONVERTER By THETA-SOFTWARE http://www.tcl.tk/ http://tcl.activestate.com/ http://www.purl.org/NET/Tcl-FAQ/
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE The Tcler's Wiki is a very active site that is updated by its users (i.e., by you) with lots of great information about Tcl and its extensions: http://wiki.tcl.tk/ The home page for this book contains errata for all editions. This is the only URL I control personally, and I plan to keep it up-to-date indefinitely: http://www.beedub.com/book/ The Prentice Hall Web site is: http://www.prenhall.com/ [ Team LiB ]
[ Team LiB ]
Ftp Archives These are some of the FTP sites that maintain Tcl archives: ftp://ftp.tcl.tk/pub/tcl ftp://src.doc.ic.ac.uk/packages/tcl/ ftp://ftp.luth.se/pub/unix/tcl/ ftp://ftp.sunet.se/pub/lang/tcl ftp://ftp.cs.columbia.edu/archives/tcl ftp://ftp.funet.fi/pub/languages/tcl You can use a World Wide Web browser like Mozilla, Netscape, Internet Explorer, or Lynx to access these sites. [ Team LiB ]
[ Team LiB ]
Newsgroups The comp.lang.tcl very active. It provides aBy forum for questions and answers UNREGISTERED VERSIONnewsgroup OF CHM isTO PDF CONVERTER THETA-SOFTWARE
about Tcl. Announcements about Tcl extensions and applications are posted to the comp.lang.tcl.announce newsgroup. The following web service provides a convenient way to read newsgroups. Enter comp.lang.tcl in the search field on this page: http://groups.google.com
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE [ Team LiB ]
[ Team LiB ]
Who Should Read This Book This book is meant to be useful to the beginner in Tcl as well as the expert. For the beginner and expert alike, I recommend careful study of Chapter 1, Tcl Fundamentals. The programming model of Tcl is designed to be simple, but it is different from many programming languages. The model is based on string substitutions, and it is important that you understand it properly to avoid trouble in complex cases. The remainder of the book consists of examples that demonstrate how to use Tcl and Tk productively. For your reference, each chapter has tables that summarize the Tcl commands and Tk widgets they describe. This book assumes that you have some programming experience, although you should be able to get by even if you are a complete novice. Knowledge of UNIX shell programming will help, but it is not required. Where aspects of window systems are relevant, I provide some background information. Chapter 2 describes the details of using Tcl and Tk on UNIX, Windows, and Macintosh. [ Team LiB ]
[ Team LiB ]
How to Read This Book This book is best used OF in aCHM hands-on manner, trying the examples at the computer. The book UNREGISTERED VERSION TO PDF CONVERTER By THETA-SOFTWARE
tries to fill the gap between the terse Tcl and Tk manual pages, which are complete but lack context and examples, and existing Tcl programs that may or may not be documented or well written.
I recommend the on-line manual pages for the Tcl and Tk commands. They provide a detailed reference guide to each command. This book summarizes much of the information from the UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE manual pages, but it does not provide the complete details, which can vary from release to release. HTML versions of the on-line manual pages can be found on the CD-ROM that comes with this book. [ Team LiB ]
[ Team LiB ]
On-line Examples The book comes with a CD-ROM that has source code for all of the examples, plus a selection of Tcl freeware found on the Internet. The CD-ROM is readable on UNIX, Windows, and Macintosh. There, you will find the versions of Tcl and Tk that were available as the book went to press. You can also retrieve the sources shown in the book from my personal Web site: http://www.beedub.com/book/ [ Team LiB ]
[ Team LiB ]
Typographic Conventions The more important setPDF apart with a title andBy horizontal rules, while others UNREGISTERED VERSIONexamples OF CHMare TO CONVERTER THETA-SOFTWARE
appear in-line. The examples use courier for Tcl and C code. When interesting results are returned by a Tcl command, those are presented below in oblique courier. The => is not part of the return value in the following example.
expr 5 + 8 UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE => 13
The courier font is also used when naming Tcl commands and C procedures within sentences. The usage of a Tcl command is presented in the following example. The command name and constant keywords appear in courier. Variable values appear in courier oblique. Optional arguments are surrounded with question marks.
set varname ?value?
The name of a program is in italics: xterm [ Team LiB ]
[ Team LiB ]
Hot Tips The icon in the margin marks a "hot tip" as judged by the reviewers of the book. The visual markers help you locate the more useful sections in the book. These are also listed in the index under Hot Tip. [ Team LiB ]
[ Team LiB ]
Book Organization The chapters of the book divided into seven parts. The By firstTHETA-SOFTWARE part describes basic Tcl UNREGISTERED VERSION OFare CHM TO PDF CONVERTER
features. The first chapter describes the fundamental mechanisms that characterize the Tcl language. This is an important chapter that provides the basic grounding you will need to use Tcl effectively. Even if you have programmed in Tcl already, you should review Chapter 1. Chapter 2 goes over the details of using Tcl and Tk on UNIX, Windows, and Macintosh. Chapter 3 presents a sample application, a CGI script, that illustrates typical Tcl programming. The rest of Part I covers the basic commands more detail, including string handling, data types, UNREGISTERED VERSION OFTcl CHM TO PDFin CONVERTER By THETA-SOFTWARE control flow, procedures, and scoping issues. Part I finishes with a description of the facilities for file I/O and running other programs. Part II describes advanced Tcl programming. It starts with eval, which lets you generate Tcl programs on the fly. Regular expressions provide powerful string processing. If your dataprocessing application runs slowly, you can probably boost its performance significantly with the regular expression facilities. Namespaces partition the global scope of procedures and variables. Unicode and message catalogs support internationalized applications. Libraries and packages provide a way to organize your code for sharing among projects. The introspection facilities of Tcl tell you about the internal state of Tcl. Event driven I/O helps server applications manage several clients simultaneously. Network sockets are used to implement the HTTP protocol used to fetch pages on the World Wide Web. The last few chapters in Part II describe platforms and frameworks for application development. Safe-Tcl is used to provide a secure environment to execute Tcl applets in a Web browser. TclHttpd is an extensible web server built in Tcl. You can build applications on top of this server, or embed it into your existing applications to give them a web interface. Starkits are an exciting new way to package and deploy Tcl/Tk applications. They use the new Virtual File System (VFS) facilities to embed a private file system right in the Starkit. Part III introduces Tk. It gives an overview of the toolkit facilities. A few complete examples are examined in detail to illustrate the features of Tk. Event bindings associate Tcl commands with events like keystrokes and button clicks. Part III ends with three chapters on the Tk geometry managers that provide powerful facilities for organizing your user interface. Part IV describes the Tk widgets. These include buttons, menus, scrollbars, labels, text entries, multiline and multifont text areas, drawing canvases, listboxes, and scales. The Tk widgets are highly configurable and very programmable, but their default behaviors make them easy to use as well. The resource database that can configure widgets provides an easy way to control the overall look of your application. Part V describes the rest of the Tk facilities. These include selections, keyboard focus, and standard dialogs. Fonts, colors, images, and other attributes that are common to the Tk widgets are described in detail. This part ends with a few larger Tk examples. Part VI is an introduction to C programming and Tcl. The goal of this part is to get you started in the right direction when you need to extend Tcl with new commands written in C or integrate Tcl into custom applications. Part VII provides a chapter for each of the Tcl/Tk releases covered by the book. These chapters provide details about what features were changed and added. They also provide a quick reference if you need to update a program or start to use a new version.
[ Team LiB ]
[ Team LiB ]
What's New in the Fourth Edition The fourthVERSION edition is up-to-date Tcl/TkCONVERTER 8.4, which addsBy many new features. Tcl has a new UNREGISTERED OF CHM with TO PDF THETA-SOFTWARE Virtual File System (VFS) feature that lets you transparently embed a file system in your application, or make remote resources such as FTP and Web sites visible through the regular file system interface. Chapter 22 is a new chapter on Tclkit and Starkits that use the Metakit embedded database to store scripts and other files. The VFS makes these files appear in a private file system. Starkits provide a new way to package and deploy Tcl/Tk applications. Chapter 21VERSION is a new chapter on using the multi-threading in Tcl. This is very useful UNREGISTERED OF CHM TO PDF CONVERTER support By THETA-SOFTWARE when embedding Tcl in threaded server applications. There are a number of new Tk features, including three new widgets. The spinbox (i.e., combobox) is like an entry widget with a dropdown selection box. The labeled frame provides a new way to decorate frames. The panedwindow is a specialized geometry manager that provides a new way to organize your user interfaces. [ Team LiB ]
[ Team LiB ]
Other Tcl Books This book was the second Tcl book after the original book by John Ousterhout, the creator of Tcl. Since then, many other Tcl books have been published. The following are just some of the books currently available. Tcl/Tk: A Developer's Guide, 2nd Ed. (Academic Press, 2003) by Clif Flynt is a good exampleoriented book that has been recently updated. Tcl and the Tk Toolkit (Addison-Wesley, 1994) by John Ousterhout provides a broad overview of all aspects of Tcl and Tk, even though it covers only Tcl 7.3 and Tk 3.6. The book provides a more detailed treatment of C programming for Tcl extensions. Exploring Expect (O'Reilly & Associates, Inc., 1995) by Don Libes is a great book about an extremely useful Tcl extension. Expect lets you automate the use of interactive programs like ftp and telnet that expect to interact with a user. By combining Expect and Tk, you can create graphical user interfaces for old applications that you cannot modify directly. Tcl/Tk in a Nutshell (O'Reilly, 1999) by Paul Raines and Jeff Tranter is a handy reference guide. It covers several popular extensions including Expect, [incr Tcl], Tix, TclX, BLT, SybTcl, OraTcl, and TclODBC. There is a tiny pocket-reference guide for Tcl/Tk that may eliminate the need to thumb through my large book to find the syntax of a particular Tcl or Tk command. Web Tcl Complete (McGraw Hill, 1999) by Steve Ball describes programming with the Tcl Web Server. It also covers Tcl/Java integration using TclBlend. [incr Tcl] From The Ground Up (Osborn-McGraw Hill, 1999) by Chad Smith describes the [incr Tcl] object-oriented extension to Tcl. Tcl/Tk for Programmers (IEEE Computer Society, 1998) by Adrian Zimmer describes Unix and Windows programming with Tcl/Tk. This book also includes solved exercises at the end of each chapter. Building Network Management Tools with Tcl/Tk (Prentice Hall, 1998) by Dave Zeltserman and Gerald Puoplo. This describes how to build SNMP tools. Graphical Applications with Tcl & Tk (M&T Books, 1997) by Eric Johnson is oriented toward Windows users. The second edition covers Tcl/Tk 8.0. Tcl/Tk Tools (O'Reilly & Associates, Inc., 1997) by Mark Harrison describes many useful Tcl extensions. These include Oracle and Sybase interfaces, object-oriented language enhancements, additional Tk widgets, and much more. The chapters were contributed by the authors of the extensions, so they provide authoritative information on some excellent additions to the Tcl toolbox. Effective Tcl/Tk Programming (Addison Wesley, 1997) by Michael McLennan and Mark Harrison illustrate Tcl and Tk with examples and application design guidelines. [ Team LiB ]
[ Team LiB ]
First Edition Thanks I would like to thank my colleagues at XeroxBy PARC for their patience with me as UNREGISTERED VERSION OFmanagers CHM TOand PDF CONVERTER THETA-SOFTWARE
I worked on this book. The tips and tricks in this book came partly from my own work as I helped lab members use Tcl, and partly from them as they taught me. Dave Nichols' probing questions forced me to understand the basic mechanisms of the Tcl interpreter. Dan Swinehart and Lawrence Butcher kept me sharp with their own critiques. Ron Frederick and Berry Kerchival adopted Tk for their graphical interfaces and amazed me with their rapid results. Becky Burwell, Rich Gold, John Maxwell, Ken Pier, Marvin Theimer, and Mohan UNREGISTERED VERSION OF Carl CHMHauser, TO PDF CONVERTER By THETA-SOFTWARE Vishwanath made use of my early drafts, and their questions pointed out large holes in the text. Karin Petersen, Bill Schilit, and Terri Watson kept life interesting by using Tcl in very nonstandard ways. I especially thank my managers, Mark Weiser and Doug Terry, for their understanding and support. I thank John Ousterhout for Tcl and Tk, which are wonderful systems built with excellent craftsmanship. John was kind enough to provide me with an advance version of Tk 4.0 so that I could learn about its new features well before its first beta release. Thanks to the Tcl programmers out on the Net, from whom I learned many tricks. John LoVerso and Stephen Uhler are the hottest Tcl programmers I know. Many thanks to the patient reviewers of early drafts: Pierre David, Clif Flynt, Simon Kenyon, Eugene Lee, Don Libes, Lee Moore, Joe Moss, Hador Shemtov, Frank Stajano, Charles Thayer, and Jim Thornton. Many folks contributed suggestions by email: Miguel Angel, Stephen Bensen, Jeff Blaine, Tom Charnock, Brian Cooper, Patrick D'Cruze, Benoit Desrosiers, Ted Dunning, Mark Eichin, Paul Friberg, Carl Gauthier, David Gerdes, Klaus Hackenberg, Torkle Hasle, Marti Hearst, Jean-Pierre Herbert, Jamie Honan, Norman Klein, Joe Konstan, Susan Larson, Håkan Liljegren, Lionel Mallet, Dejan Milojicic, Greg Minshall, Bernd Mohr, Will Morse, Heiko Nardmann, Gerd Neugebauer, TV Raman, Cary Renzema, Rob Riepel, Dan Schenk, Jean-Guy Schneider, Elizabeth Scholl, Karl Schwamb, Rony Shapiro, Peter Simanyi, Vince Skahan, Bill Stumbo, Glen Vanderburg, Larry Virden, Reed Wade, and Jim Wight. Unfortunately, I could not respond to every suggestion, even some that were excellent. Thanks to the editors and staff at Prentice Hall. Mark Taub has been very helpful as I progressed through my first book. Lynn Schneider and Kerry Reardon were excellent copy and production editors, respectively. [ Team LiB ]
[ Team LiB ]
Second Edition Thanks I get to thank John Ousterhout again, this time for supporting me as I worked in the Tcl/Tk group at Sun Microsystems. The rest of the group deserve a lot of credit for turning Tcl and Tk into a dynamite cross-platform solution. Scott Stanton led the Tk port to the PC. Ray Johnson led the Tk port to the Macintosh. Jacob Levy implemented the event-driven I/O system, SafeTcl, and the browser plug-in. Brian Lewis built the Tcl compiler. Ken Corey worked on Java integration and helped with the SpecTcl user interface builder. Syd Polk generalized the menu system to work with native widgets on the Macintosh and Windows. Colin Stevens generalized the font mechanism and worked on internationalization for Tk. Stephen Uhler deserves special thanks for inspiring many of the cool examples I use in this book. He was the lead on the SpecTcl user interface builder. He built the core HTML display library on which I based an editor. We worked closely together on the first versions of TclHttpd. He taught me how to write compact, efficient Tcl code and to use regular expression substitutions in amazing ways. I hope he has learned at least a little from me. Thanks again to Mark Taub, Eileen Clark, and Martha Williams at Prentice Hall. George Williams helped me assemble the files for the CD-ROM. [ Team LiB ]
[ Team LiB ]
Third Edition Thanks John Ousterhout continues his wonderful as Tcl benefactor, now as founder of Scriptics UNREGISTERED VERSION OF CHM TO PDFrole CONVERTER By THETA-SOFTWARE
Corporation. I'd like to thank every one of the great folks that I work with at Scriptics, especially the pioneering crew of Sarah Daniels, Scott Stanton, Ray Johnson, Bryan Surles, Melissa Chawla, Lee Bernhard, Suresh Sastry, Emil Scaffon, Pat P., Scott Redman, and Berry Kercheval. The rest of the gang deserves a big thanks for making Scriptics such an enjoyable place to work. Jerry Peek, who is a notable author himself, provided valuable advice and wonderfully detailed comments! Ken PDF JonesCONVERTER told me about aBy great indexing tool. UNREGISTERED VERSION OF CHM TO THETA-SOFTWARE I'd like to thank all the readers that drop me the encouraging note or probing question via email. I am always interested in new and interesting uses of Tcl! Thanks to the editors at Prentice Hall: Mark Taub, Joan McNamara, and Joan Eurell. Mark continues to encourage me to come out with new editions, and the Joans helped me complete this third edition on time. [ Team LiB ]
[ Team LiB ]
Fourth Edition Thanks I'd like to thank Jeff Hobbs and Ken Jones for making this project happen. Jeff has done a great service to the Tcl community as "The Tcl Guy". His leadership and hard work have been responsible for the steady pace of new Tcl/Tk releases. Ken is a great Tcl teacher and his experiences teaching are reflected in his additions to the book for this 4th edition. Again, without these two lending a hand, I just wouldn't have found the time for this edition. I'd like to thank the Tcl Core Team and the supporting cast of contributors to the Tcl/Tk code base. The TCT provides a great framework to keep Tcl a high quality software product that continues to adopt new an interesting features. I'd like to thank Jean-Claude Wippler and Steve Landers for Metakit, Tclkit, and Starkits. These provide a delightful way to package and deploy Tcl applications. I expect to see a lot more from these technologies in the future. Several readers provided great feedback on the Starkit material: Robert Techentin, Steve Blinkhorn, Frank Sergeant, Arjen Markus, Uwe Koloska, Larry Virden, Tom Krehbiel, and Donald Porter. I'd like to thank Prentice Hall for their continued support. Mark Taub continues his role as godfather of this book. Kathleen Caren was the able production editor for this edition. Finally, I thank my wonderful wife Jody for her love, kindness, patience, wit, and understanding as I worked long hours. Happily, many of those hours were spent working from home. I now have three sons, Christopher, Daniel, and Michael, who get the credit for keeping me from degenerating into a complete nerd. [ Team LiB ]
[ Team LiB ]
Contact the Author I am always open to comments this CONVERTER book. My email address is [email protected] . It helps UNREGISTERED VERSION OF CHM about TO PDF By THETA-SOFTWARE me sort through my mail if you put the word "book" or the title of the book into the email subject line. Visit my Web site for current news about the book and my other interests. I maintain an errata page for each edition, so please consult that and feel free to send bug reports!
http://www.beedub.com/ UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE [ Team LiB ]
[ Team LiB ]
Part I: Tcl Basics Part I introduces the basics of Tcl. Everyone should read Chapter 1, which describes the fundamental properties of the language. Tcl is really quite simple, so beginners can pick it up quickly. The experienced programmer should review Chapter 1 to eliminate any misconceptions that come from using other languages. Chapter 2 is a short introduction to running Tcl and Tk on UNIX, Windows, and Macintosh systems. You may want to look at this chapter first so you can try out the examples as you read Chapter 1. Chapter 3 presents a sample application, a CGI script, that implements a guestbook for a Web site. The example uses several facilities that are described in detail in later chapters. The goal is to provide a working example that illustrates the power of Tcl. The rest of Part I covers basic programming with Tcl. Simple string processing is covered in Chapter 4. Tcl lists, which share the syntax rules of Tcl commands, are explained in Chapter 5. Control structure like loops and if statements are described in Chapter 6. Chapter 7 describes Tcl procedures, which are new commands that you write in Tcl. Chapter 8 discusses Tcl arrays. Arrays are the most flexible and useful data structure in Tcl. Chapter 9 describes file I/O and running other programs. These facilities let you build Tcl scripts that glue together other programs and process data in files. After reading Part I you will know enough Tcl to read and understand other Tcl programs, and to write simple programs yourself. [ Team LiB ]
[ Team LiB ]
Chapter 1. Tcl Fundamentals UNREGISTERED VERSION TO PDF CONVERTER By THETA-SOFTWARE This chapter describesOF the CHM basic syntax rules for the Tcl scripting language. It describes the basic mechanisms used by the Tcl interpreter: substitution and grouping. It touches lightly on the following Tcl commands: puts, format, set, expr, string, while, incr, and proc. Tcl is a string-based command language. The language has only a few fundamental constructs and relatively little syntax, which makes it easy to learn. The Tcl syntax is meant to be simple. UNREGISTERED VERSION TO PDF CONVERTER Byblocks THETA-SOFTWARE Tcl is designed to be a OF glueCHM that assembles software building into applications. A simpler glue makes the job easier. In addition, Tcl is interpreted when the application runs. The interpreter makes it easy to build and refine your application in an interactive manner. A great way to learn Tcl is to try out commands interactively. If you are not sure how to run Tcl on your system, see Chapter 2 for instructions for starting Tcl on UNIX, Windows, and Macintosh systems. This chapter takes you through the basics of the Tcl language syntax. Even if you are an expert programmer, it is worth taking the time to read these few pages to make sure you understand the fundamentals of Tcl. The basic mechanisms are all related to strings and string substitutions, so it is fairly easy to visualize what is going on in the interpreter. The model is a little different from some other programming languages with which you may already be familiar, so it is worth making sure you understand the basic concepts. [ Team LiB ]
[ Team LiB ]
Tcl Commands Tcl stands for Tool Command Language. A command does something for you, like output a string, compute a math expression, or display a widget on the screen. Tcl casts everything into the mold of a command, even programming constructs like variable assignment and procedure definition. Tcl adds a tiny amount of syntax needed to properly invoke commands, and then it leaves all the hard work up to the command implementation. The basic syntax for a Tcl command is:
command arg1 arg2 arg3 ...
The command is either the name of a built-in command or a Tcl procedure. White space (i.e., spaces or tabs) is used to separate the command name and its arguments, and a newline (i.e., the end of line character) or semicolon is used to terminate a command. Tcl does not interpret the arguments to the commands except to perform grouping, which allows multiple words in one argument, and substitution, which is used with programming variables and nested command calls. The behavior of the Tcl command processor can be summarized in three basic steps:
Argument grouping. Value substitution of nested commands, variables, and backslash escapes. Command invocation. It is up to the command to interpret its arguments. This model is described in detail in this Chapter. [ Team LiB ]
[ Team LiB ]
Hello, World! Example 1-1 TheOF "Hello, World!" example By THETA-SOFTWARE UNREGISTERED VERSION CHM TO PDF CONVERTER puts stdout {Hello, World!} => Hello, World!
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE In this example, the command is puts, which takes two arguments: an I/O stream identifier and a string. puts writes the string to the I/O stream along with a trailing newline character. There are two points to emphasize: Arguments are interpreted by the command. In the example, stdout is used to identify the standard output stream. The use of stdout as a name is a convention employed by puts and the other I/O commands. Also, stderr is used to identify the standard error output, and stdin is used to identify the standard input. Chapter 9 describes how to open other files for I/O. Curly braces are used to group words together into a single argument. The puts command receives Hello, World! as its second argument.
The braces are not part of the value.
The braces are syntax for the interpreter, and they get stripped off before the value is passed to the command. Braces group all characters, including newlines and nested braces, until a matching brace is found. Tcl also uses double quotes for grouping. Grouping arguments will be described in more detail later. [ Team LiB ]
[ Team LiB ]
Variables The set command is used to assign a value to a variable. It takes two arguments: The first is the name of the variable, and the second is the value. Variable names can be any length, and case is significant. In fact, you can use any character in a variable name.
It is not necessary to declare Tcl variables before you use them.
The interpreter will create the variable when it is first assigned a value. The value of a variable is obtained later with the dollar-sign syntax, illustrated in Example 1-2:
Example 1-2 Tcl variables set var 5 => 5 set b $var => 5
The second set command assigns to variable b the value of variable var. The use of the dollar sign is our first example of substitution. You can imagine that the second set command gets rewritten by substituting the value of var for $var to obtain a new command.
set b 5
The actual implementation of substitution is more efficient, which is important when the value is large. [ Team LiB ]
[ Team LiB ]
Command Substitution The secondVERSION form of substitution command substitution. ABy nested command is delimited by UNREGISTERED OF CHM is TO PDF CONVERTER THETA-SOFTWARE
square brackets, [ ]. The Tcl interpreter takes everything between the brackets and evaluates it as a command. It rewrites the outer command by replacing the square brackets and everything between them with the result of the nested command. This is similar to the use of backquotes in other shells, except that it has the additional advantage of supporting arbitrary nesting of commands.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Example 1-3 Command substitution set len [string length foobar] => 6
In Example 1-3, the nested command is:
string length foobar
This command returns the length of the string foobar. The string command is described in detail starting on page 49. The nested command runs first. Then, command substitution causes the outer command to be rewritten as if it were:
set len 6
If there are several cases of command substitution within a single command, the interpreter processes them from left to right. As each right bracket is encountered, the command it delimits is evaluated. This results in a sensible ordering in which nested commands are evaluated first so that their result can be used in arguments to the outer command. [ Team LiB ]
[ Team LiB ]
Math Expressions The Tcl interpreter itself does not evaluate math expressions. Tcl just does grouping, substitutions and command invocations. The expr command is used to parse and evaluate math expressions.
Example 1-4 Simple arithmetic expr 7.2 / 4 => 1.8
The math syntax supported by expr is the same as the C expression syntax. The expr command deals with integer, floating point, and boolean values. Logical operations return either 0 (false) or 1 (true). Integer values are promoted to floating point values as needed. Octal values are indicated by a leading zero (e.g., 033 is 27 decimal). Hexadecimal values are indicated by a leading 0x. Scientific notation for floating point numbers is supported. A summary of the operator precedence is given on page 20. You can include variable references and nested commands in math expressions. The following example uses expr to add the value of x to the length of the string foobar. As a result of the innermost command substitution, the expr command sees 6 + 7, and len gets the value 13:
Example 1-5 Nested commands set x 7 set len [expr [string length foobar] + $x] => 13
The expression evaluator supports a number of built-in math functions. (For a complete listing, see page 21.) Example 1-6 computes the value of pi:
Example 1-6 Built-in math functions set pi [expr 2*asin(1.0)] => 3.1415926535897931
The implementation of expr is careful to preserve accurate numeric values and avoid conversions between numbers and strings. However, you can make expr operate more efficiently by grouping the entire expression in curly braces. The explanation has to do with the byte code compiler that Tcl uses internally, and its effects are explained in more detail on page 15. For now, you should be aware that these expressions are all valid and run faster than the examples shown above:
Example 1-7 Grouping expressions with braces
expr {7.2 / 4} set len [expr {[string length foobar] + $x}] set pi [expr {2*asin(1.0)}]
[ Team LiBVERSION ] UNREGISTERED OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
Backslash Substitution The final type of substitution done by the Tcl interpreter is backslash substitution. This is used to quote characters that have special meaning to the interpreter. For example, you can specify a literal dollar sign, brace, or bracket by quoting it with a backslash. As a rule, however, if you find yourself using lots of backslashes, there is probably a simpler way to achieve the effect you are striving for. In particular, the list command described on page 65 will do quoting for you automatically. In Example 1-8 backslash is used to get a literal $:
Example 1-8 Quoting special characters with backslash set dollar \$foo => $foo set x $dollar => $foo
Only a single round of interpretation is done.
The second set command in the example illustrates an important property of Tcl. The value of dollar does not affect the substitution performed in the assignment to x. In other words, the Tcl parser does not care about the value of a variable when it does the substitution. In the example, the value of x and dollar is the string $foo. In general, you do not have to worry about the value of variables until you use eval, which is described in Chapter 10. You can also use backslash sequences to specify characters with their Unicode, hexadecimal, or octal value:
set escape \u001b set escape \0x1b set escape \033
The value of variable escape is the ASCII ESC character, which has character code 27. Table 11 on page 20 summarizes backslash substitutions. A common use of backslashes is to continue long commands on multiple lines. This is necessary because a newline terminates a command. The backslash in the next example is required; otherwise the expr command gets terminated by the newline after the plus sign.
Example 1-9 Continuing long lines with backslashes
set totalLength [expr [string length $one] + \ [string length $two]]
There are two fine points to escaping newlines. First, if you are grouping an argument as described in the next section, then you do not need to escape newlines; the newlines are automatically part of the notCONVERTER terminate the command. Second, a backslash as the UNREGISTERED VERSION OFgroup CHMand TOdo PDF By THETA-SOFTWARE last character in a line is converted into a space, and all the white space at the beginning of the next line is replaced by this substitution. In other words, the backslash-newline sequence also consumes all the leading white space on the next line. [ Team LiBVERSION ] UNREGISTERED OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
Grouping with Braces and Double Quotes Double quotes and curly braces are used to group words together into one argument. The difference between double quotes and curly braces is that quotes allow substitutions to occur in the group, while curly braces prevent substitutions. This rule applies to command, variable, and backslash substitutions.
Example 1-10 Grouping with double quotes vs. braces set s Hello => Hello puts stdout "The => The length of puts stdout {The => The length of
length of $s is [string length $s]." Hello is 5. length of $s is [string length $s].} $s is [string length $s].
In the second command of Example 1-10, the Tcl interpreter does variable and command substitution on the second argument to puts. In the third command, substitutions are prevented, so the string is printed as is. In practice, grouping with curly braces is used when substitutions on the argument must be delayed until a later time (or never done at all). Examples include loops, conditional statements, and procedure declarations. Double quotes are useful in simple cases like the puts command previously shown. Another common use of quotes is with the format command. This is similar to the C printf function. The first argument to format is a format specifier that often includes special characters like newlines, tabs, and spaces. The easiest way to specify these characters is with backslash sequences (e.g., \n for newline and \t for tab). The backslashes must be substituted before the format command is called, so you need to use quotes to group the format specifier.
puts [format "Item: %s\t%5.3f" $name $value]
Here format is used to align a name and a value with a tab. The %s and %5.3f indicate how the remaining arguments to format are to be formatted. Note that the trailing \n usually found in a C printf call is not needed because puts provides one for us. For more information about the format command, see page 56.
Square Brackets Do Not Group The square bracket syntax used for command substitution does not provide grouping. Instead, a nested command is considered part of the current group. In the command below, the double quotes group the last argument, and the nested command is just part of that group.
puts stdout "The length of $s is [string length $s]."
If an argument is made up of only a nested command, you do not need to group it with doublequotes because the Tcl parser treats the whole nested command as part of the group.
puts stdout [string length $s]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE The following is a redundant use of double quotes:
puts stdout "[expr $x + $y]"
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Grouping before Substitution The Tcl parser makes a single pass through a command as it makes grouping decisions and performs string substitutions. Grouping decisions are made before substitutions are performed, which is an important property of Tcl. This means that the values being substituted do not affect grouping because the grouping decisions have already been made. The following example demonstrates how nested command substitution affects grouping. A nested command is treated as an unbroken sequence of characters, regardless of its internal structure. It is included with the surrounding group of characters when collecting arguments for the main command.
Example 1-11 Embedded command and variable substitution set x 7; set y 9 puts stdout $x+$y=[expr $x + $y] => 7+9=16
In Example 1-11, the second argument to puts is:
$x+$y=[expr $x + $y]
The white space inside the nested command is ignored for the purposes of grouping the argument. By the time Tcl encounters the left bracket, it has already done some variable substitutions to obtain:
7+9=
When the left bracket is encountered, the interpreter calls itself recursively to evaluate the nested command. Again, the $x and $y are substituted before calling expr. Finally, the result of expr is substituted for everything from the left bracket to the right bracket. The puts command gets the following as its second argument:
7+9=16
Grouping before substitution.
The point of this example is that the grouping decision about puts's second argument is made before the command substitution is done. Even if the result of the nested command contained spaces or other special characters, they would be ignored for the purposes of grouping the arguments to the outer command. Grouping and variable substitution interact the same as grouping and command substitution. Spaces or special characters in variable values do not affect grouping decisions because these decisions are made before the variable values are substituted. If you want the output to look nicer in the example, with spaces around the + and =, then you must use double quotes to explicitly group the argument to puts:
puts stdout "$x + $y = [expr $x + $y]"
The double quotes are used for grouping in this case to allow the variable and command substitution on the argument to puts.
Grouping Math Expressions with Braces It turns out that expr does its own substitutions inside curly braces. This is explained in more detail on page 15. This means you can write commands like the one below and the substitutions on the variables in the expression still occur:
puts stdout "$x + $y = [expr {$x + $y}]"
More Substitution Examples If you have several substitutions with no white space between them, you can avoid grouping with quotes. The following command sets concat to the value of variables a, b, and c all concatenated together:
set concat $a$b$c
Again, if you want to add spaces, you'll need to use quotes:
set concat "$a $b $c"
In general, you can place a bracketed command or variable reference anywhere. The following computes a command name:
[findCommand $x] arg arg
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE When you use Tk, you often use widget names as command names:
$text insert end "Hello, World!"
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE [ Team LiB ]
[ Team LiB ]
Procedures Tcl uses the proc command to define procedures. Once defined, a Tcl procedure is used just like any of the other built-in Tcl commands. The basic syntax to define a procedure is:
proc name arglist body
The first argument is the name of the procedure being defined. The second argument is a list of parameters to the procedure. The third argument is a command body that is one or more Tcl commands. The procedure name is case sensitive, and in fact it can contain any characters. Procedure names and variable names do not conflict with each other. As a convention, this book begins procedure names with uppercase letters and it begins variable names with lowercase letters. Good programming style is important as your Tcl scripts get larger. Tcl coding style is discussed in Chapter 12.
Example 1-12 Defining a procedure proc Diag {a b} { set c [expr {sqrt($a * $a + $b * $b)}] return $c } puts "The diagonal of a 3, 4 right triangle is [Diag 3 4]" => The diagonal of a 3, 4 right triangle is 5.0
The Diag procedure defined in the example computes the length of the diagonal side of a right triangle given the lengths of the other two sides. The sqrt function is one of many math functions supported by the expr command. The variable c is local to the procedure; it is defined only during execution of Diag. Variable scope is discussed further in Chapter 7. It is not really necessary to use the variable c in this example. The procedure can also be written as:
proc Diag {a b} { return [expr {sqrt($a * $a + $b * $b)}] }
The return command is used to return the result of the procedure. The return command is optional in this example because the Tcl interpreter returns the value of the last command in the body as the value of the procedure. So, the procedure could be reduced to:
proc Diag {a b} { expr {sqrt($a * $a + $b * $b)} }
Note the stylized use of curly braces in the example. The curly brace at the end of the first line starts the third argument to proc, which is the command body. In this case, the Tcl interpreter sees the opening left brace, causing it to ignore newline characters and scan the text until a matching right brace is found. Double quotes have the same property. They group characters, including newlines, until another double quote is found. The result of the grouping is that the third argument to proc is a sequence of commands. When they are evaluated later, the embedded newlines will terminate each command.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
The other crucial effect of the curly braces around the procedure body is to delay any substitutions in the body until the time the procedure is called. For example, the variables a, b, and c are not defined until the procedure is called, so we do not want to do variable substitution at the time Diag is defined. The proc command supports additional features such as having variable numbers of arguments
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE and default values for arguments. These are described in detail in Chapter 7. [ Team LiB ]
[ Team LiB ]
A Factorial Example To reinforce what we have learned so far, below is a longer example that uses a while loop to compute the factorial function:
Example 1-13 A while loop to compute factorial proc Factorial {x} { set i 1; set product 1 while {$i <= $x} { set product [expr {$product * $i}] incr i } return $product } Factorial 10 => 3628800
The semicolon is used on the first line to remind you that it is a command terminator just like the newline character. The while loop is used to multiply all the numbers from one up to the value of x. The first argument to while is a boolean expression, and its second argument is a command body to execute. The while command and other control structures are described in Chapter 6. The same math expression evaluator used by the expr command is used by while to evaluate the boolean expression. There is no need to explicitly use the expr command in the first argument to while, even if you have a much more complex expression. The loop body and the procedure body are grouped with curly braces in the same way. The opening curly brace must be on the same line as proc and while. If you like to put opening curly braces on the line after a while or if statement, you must escape the newline with a backslash:
while {$i < $x} \ { set product ... }
Always group expressions and command bodies with curly braces.
Curly braces around the boolean expression are crucial because they delay variable substitution until the while command implementation tests the expression. The following example is an infinite loop:
set i 1; while $i<=10 {incr i}
UNREGISTERED VERSION OF CHM TOreason PDF CONVERTER By THETA-SOFTWARE [*] The The loop will run indefinitely. is that the Tcl interpreter will substitute for $i before while is called, so while gets a constant expression 1<=10 that will always be true. You can avoid these kinds of errors by adopting a consistent coding style that groups expressions with curly braces: [*]
Ironically, Tcl 8.0 introduced a byte-code compiler, and the first releases of Tcl 8.0 had a bug in the
compiler that caused thisCHM loop toTO terminate! This bug is fixed in theTHETA-SOFTWARE 8.0.5 patch release. UNREGISTERED VERSION OF PDF CONVERTER By
set i 1; while {$i<=10} {incr i}
The incr command is used to increment the value of the loop variable i. This is a handy command that saves us from the longer command:
set i [expr {$i + 1}]
The incr command can take an additional argument, a positive or negative integer by which to change the value of the variable. Using this form, it is possible to eliminate the loop variable i and just modify the parameter x. The loop body can be written like this:
while {$x > 1} { set product [expr {$product * $x}] incr x -1 }
Example 1-14 shows factorial again, this time using a recursive definition. A recursive function is one that calls itself to complete its work. Each recursive call decrements x by one, and when x is one, then the recursion stops.
Example 1-14 A recursive definition of factorial proc Factorial {x} { if {$x <= 1} { return 1 } else { return [expr {$x * [Factorial [expr {$x - 1}]]}] } }
[ Team LiB ]
[ Team LiB ]
More about Variables The set command will return the value of a variable if it is only passed a single argument. It treats that argument as a variable name and returns the current value of the variable. The dollar-sign syntax used to get the value of a variable is really just an easy way to use the set command. Example 1-15 shows a trick you can play by putting the name of one variable into another variable:
Example 1-15 Using set to return a variable value set var {the value of var} => the value of var set name var => var set name => var set $name => the value of var
This is a somewhat tricky example. In the last command, $name gets substituted with var. Then, the set command returns the value of var, which is the value of var. Nested set commands provide another way to achieve a level of indirection. The last set command above can be written as follows:
set [set name] => the value of var
Using a variable to store the name of another variable may seem overly complex. However, there are some times when it is very useful. There is even a special command, upvar, that makes this sort of trick easier. The upvar command is described in detail in Chapter 7.
Funny Variable Names The Tcl interpreter makes some assumptions about variable names that make it easy to embed variable references into other strings. By default, it assumes that variable names contain only letters, digits, and the underscore. The construct $foo.o represents a concatenation of the value of foo and the literal ".o". If the variable reference is not delimited by punctuation or white space, then you can use curly braces to explicitly delimit the variable name (e.g., ${x}). You can also use this to reference variables with funny characters in their name, although you probably do not want variables named like that. If you find yourself using funny variable names, or computing the names of variables, then you may want to use the upvar command.
Example 1-16 Embedded variable references
set foo filename set object $foo.o => filename.o set a AAA set b abc${a}def => abcAAAdef UNREGISTERED VERSION set .o yuk! set x ${.o}y => yuk!y
OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE The unset Command You can delete a variable with the unset command:
unset ?-nocomplain? ?--? varName varName2 ...
Any number of variable names can be passed to the unset command. However, unset will raise an error if a variable is not already defined, unless the -nocomplain is given. Use -- to unset a variable named -nocomplain.
Using info to Find Out about Variables The existence of a variable can be tested with the info exists command. For example, because incr requires that a variable exist, you might have to test for the existence of the variable first.
Example 1-17 Using info to determine if a variable exists if {![info exists foobar]} { set foobar 0 } else { incr foobar }
Example 7-6 on page 92 implements a version of incr which handles this case.
[ Team LiB ]
[ Team LiB ]
More about Math Expressions This section describes a few fine points about math in Tcl scripts. In Tcl 7.6 and earlier versions math is not that efficient because of conversions between strings and numbers. The expr command must convert its arguments from strings to numbers. It then does all its computations with double precision floating point values. The result is formatted into a string that has, by default, 12 significant digits. This number can be changed by setting the tcl_precision variable to the number of significant digits desired. Seventeen digits of precision are enough to ensure that no information is lost when converting back and forth between a string and an IEEE double precision number:
Example 1-18 Controlling precision with tcl_precision expr 1 / 3 => 0 expr 1 / 3.0 => 0.333333333333 set tcl_precision 17 => 17 expr 1 / 3.0 # The trailing 1 is the IEEE rounding digit => 0.33333333333333331
In Tcl 8.0 and later versions, the overhead of conversions is eliminated in most cases by the built-in compiler. Even so, Tcl was not designed to support math-intensive applications. You may want to implement math-intensive code in a compiled language and register the function as a Tcl command as described in Chapter 47. There is support for string comparisons by expr, so you can test string values in if statements. You must use quotes so that expr knows to do string comparisons:
if {$answer == "yes"} { ... }
However, the string compare and string equal commands described in Chapter 4 are more reliable because expr may do conversions on strings that look like numbers. The issues with string operations and expr are discussed on page 52. Tcl 8.4 introduced eq and ne expr operators to allow strict string based comparison. Expressions can include variable and command substitutions and still be grouped with curly braces. This is because an argument to expr is subject to two rounds of substitution: one by the Tcl interpreter, and a second by expr itself. Ordinarily this is not a problem because math values do not contain the characters that are special to the Tcl interpreter. The second round of substitutions is needed to support commands like while and if that use the expression evaluator internally.
Grouping expressions can make them run more efficiently.
UNREGISTERED OFexpressions CHM TO PDF CONVERTER Byexpr THETA-SOFTWARE You shouldVERSION always group in curly braces and let do command and variable substitutions. Otherwise, your values may suffer extra conversions from numbers to strings and back to numbers. Not only is this process slow, but the conversions can lose precision in certain circumstances. For example, suppose x is computed from a math function:
set x [expr {sqrt(2.0)}] UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE At this point the value of x is a double-precision floating point value, just as you would expect. If you do this:
set two [expr $x * $x]
then you may or may not get 2.0 as the result! This is because Tcl will substitute $x and expr will concatenate all its arguments into one string, and then parse the expression again. In contrast, if you do this:
set two [expr {$x * $x}]
then expr will do the substitutions, and it will be careful to preserve the floating point value of x. The expression will be more accurate and run more efficiently because no string conversions will be done. The story behind Tcl values is described in more detail in Chapter 47 on C programming and Tcl. [ Team LiB ]
[ Team LiB ]
Comments Tcl uses the pound character, #, for comments. Unlike in many other languages, the # must occur at the beginning of a command. A # that occurs elsewhere is not treated specially. An easy trick to append a comment to the end of a command is to precede the # with a semicolon to terminate the previous command:
# Here are some parameters set rate 7.0 ;# The interest rate set months 60 ;# The loan term
One subtle effect to watch for is that a backslash effectively continues a comment line onto the next line of the script. In addition, a semicolon inside a comment is not significant. Only a newline terminates comments:
# Here is the start of a Tcl comment \ and some more of it; still in the comment
The behavior of a backslash in comments is pretty obscure, but it can be exploited as shown in Example 2-3 on page 27. A surprising property of Tcl comments is that curly braces inside comments are still counted for the purposes of finding matching brackets. The motivation for this odd feature was to keep the original Tcl parser simpler. However, it means that the following will not work as expected to comment out an alternate version of an if expression:
# if {boolean expression1} { if {boolean expression2} { some commands }
The previous sequence results in an extra left curly brace, and probably a complaint about a missing close brace at the end of your script! A technique I use to comment out large chunks of code is to put the code inside an if block that will never execute:
if {0} { unused code here }
[ Team LiB ]
[ Team LiB ]
Substitution and Grouping Summary UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
The following rules summarize the fundamental mechanisms of grouping and substitution that are performed by the Tcl interpreter before it invokes a command: Command arguments are separated by white space, unless arguments are grouped with curly braces or double quotes as described below.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Grouping with curly braces, { }, prevents substitutions. Braces nest. The interpreter includes all characters between the matching left and right brace in the group, including newlines, semicolons, and nested braces. The enclosing (i.e., outermost) braces are not included in the group's value. Grouping with double quotes, " ", allows substitutions. The interpreter groups everything until another double quote is found, including newlines and semicolons. The enclosing quotes are not included in the group of characters. A double-quote character can be included in the group by quoting it with a backslash, (e.g., \"). Grouping decisions are made before substitutions are performed, which means that the values of variables or command results do not affect grouping. A dollar sign, $, causes variable substitution. Variable names can be any length, and case is significant. If variable references are embedded into other strings, or if they include characters other than letters, digits, and the underscore, they can be distinguished with the ${varname} syntax. Square brackets, [ ], cause command substitution. Everything between the brackets is treated as a command, and everything including the brackets is replaced with the result of the command. Nesting is allowed. The backslash character, \, is used to quote special characters. You can think of this as another form of substitution in which the backslash and the next character or group of characters are replaced with a new character. Substitutions can occur anywhere unless prevented by curly brace grouping. Part of a group can be a constant string, and other parts of it can be the result of substitutions. Even the command name can be affected by substitutions. A single round of substitutions is performed before command invocation. The result of a substitution is not interpreted a second time. This rule is important if you have a variable value or a command result that contains special characters such as spaces, dollar signs, square brackets, or braces. Because only a single round of substitution is done, you do not have to worry about special characters in values causing extra substitutions. [ Team LiB ]
[ Team LiB ]
Fine Points A common error is to forget a space between arguments when grouping with braces or quotes. This is because white space is used as the separator, while the braces or quotes only provide grouping. If you forget the space, you will get syntax errors about unexpected characters after the closing brace or quote. The following is an error because of the missing space between } and {: if {$x > 1}{puts "x = $x"}
A double quote is only used for grouping when it comes after white space. This means you can include a double quote in the middle of a group without quoting it with a backslash. This requires that curly braces or white space delimit the group. I do not recommend using this obscure feature, but this is what it looks like: set silly a"b
When double quotes are used for grouping, the special effect of curly braces is turned off. Substitutions occur everywhere inside a group formed with double quotes. In the next command, the variables are still substituted: set x xvalue set y "foo {$x} bar" => foo {xvalue} bar
When double quotes are used for grouping and a nested command is encountered, the nested command can use double quotes for grouping, too. puts "results [format "%f %f" $x $y]"
Spaces are not required around the square brackets used for command substitution. For the purposes of grouping, the interpreter considers everything between the square brackets as part of the current group. The following sets x to the concatenation of two command results because there is no space between ] and [. set x [cmd1][cmd2]
Newlines and semicolons are ignored when grouping with braces or double quotes. They get included in the group of characters just like all the others. The following sets x to a string that contains newlines: set x "This is line one. This is line two. This is line three."
During command substitution, newlines and semicolons are significant as command terminators. If you have a long command that is nested in square brackets, put a backslash before the newline if you want to continue the command on another line. This was illustrated in Example 1-9 on page 8. A dollar sign followed by something other than a letter, digit, underscore, or left parenthesis is treated as a literal dollar sign. The following sets x to the single character $.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE set x $ [ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
Reference Backslash Sequences
Table 1-1. Backslash sequences \a
Bell. (0x7)
\b
Backspace. (0x8)
\f
Form feed. (0xc)
\n
Newline. (0xa)
\r
Carriage return. (0xd)
\t
Tab. (0x9)
\v
Vertical tab. (0xb)
\ Replace the newline and the leading white space on the next line with a space. \\
Backslash. ('\')
\ooo
Octal specification of character code. 1, 2, or 3 octal digits (0-7).
\xhh
Hexadecimal specification of character code. 1 or 2 hex digits. Be careful when using this in a string of characters, because all hexadecimal characters following the \x will be consumed, but only the last 2 will specify the value.
\uhhhh
Hexadecimal specification of a 16-bit Unicode character value. 4 hex digits.
\c
Replaced with literal c if c is not one of the cases listed above. In particular, \$, \", \{, \}, \], and \[ are used to obtain these characters.
Arithmetic Operators
Table 1-2. Arithmetic operators from highest to lowest precedence
- ~ !
Unary minus, bitwise NOT, logical NOT.
* / %
Multiply, divide, remainder.
+ -
Add, subtract.
<< >>
Left shift, right shift.
< > <= >=
Comparison: less, greater, less or equal, greater or equal.
== != eq ne
Equal, not equal, string equal (Tcl 8.4), string not equal (Tcl 8.4).
&
Bitwise AND.
^
Bitwise XOR.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
| Bitwise UNREGISTERED VERSION OFOR. CHM TO PDF CONVERTER By THETA-SOFTWARE &&
Logical AND.
||
Logical OR.
x?y:z
If x then y else z.
Built-in Math Functions
Table 1-3. Built-in math functions acos(x)
Arccosine of x.
asin(x)
Arcsine of x.
atan(x)
Arctangent of x.
atan2(y,x) Rectangular (x,y) to polar (r,th). atan2 gives th. ceil(x)
Least integral value greater than or equal to x.
cos(x)
Cosine of x.
cosh(x)
Hyperbolic cosine of x.
exp(x)
Exponential, ex.
floor(x)
Greatest integral value less than or equal to x.
fmod(x,y)
Floating point remainder of x/y.
hypot(x,y) Returns sqrt(x*x + y*y). r part of polar coordinates. log(x)
Natural log of x.
log10(x)
Log base 10 of x.
pow(x,y)
x to the y power, xy.
sin(x)
Sine of x.
sinh(x)
Hyperbolic sine of x.
sqrt(x)
Square root of x.
tan(x)
Tangent of x.
tanh(x)
Hyperbolic tangent of x.
abs(x)
Absolute value of x.
double(x)
Promote x to floating point.
int(x)
Truncate x to an integer.
round(x)
Round x to an integer.
rand()
Return a random floating point value between 0.0 and 1.0.
srand(x)
Set the seed for the random number generator to the integer x.
wide(x)
Promote x to a wide (64-bit) integer. (Tcl 8.4)
Core Tcl Commands The pages listed in Table 1-4 give the primary references for the command.
Table 1-4. Built-in Tcl commands Command after
Pg.
Description
228 Schedule a Tcl command for later execution.
append
56 Append arguments to a variable's value. No spaces added.
array
97 Query array state and search through elements.
binary
59 Convert between strings and binary data.
break
83 Exit loop prematurely.
catch
83 Trap errors.
cd
122 Change working directory.
clock
183 Get the time and format date strings.
close
121 Close an open I/O stream.
concat
65 Concatenate arguments with spaces between. Splices lists.
console
29 Control the console used to enter commands interactively.
continue
83 Continue with next loop iteration.
error
85 Raise an error.
eof
116 Check for end of file.
eval
130 Concatenate arguments and evaluate them as a command.
exec
105 Fork and execute a UNIX program.
exit
124 Terminate the process.
expr
6 Evaluate a math expression.
Command fblocked
Pg.
Description
233 Poll an I/O channel to see if data is ready.
fconfigure 231 Set and query I/O channel properties. fcopy
250 Copy from one I/O channel to another.
file
108 Query the file system.
fileevent
229 Register callback for event-driven I/O.
flush
116 Flush output from an I/O stream's internal buffers.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
for
82 Loop construct similar to C for statement.
foreach VERSION 79 Loop over a list, or lists, of values. UNREGISTERED OFconstruct CHM TO PDF CONVERTER By THETA-SOFTWARE format
56 Format a string similar to C sprintf.
gets
119 Read a line of input from an I/O stream.
glob
122 Expand a pattern to matching file names.
global history
90 Declare global variables. 196 Use command-line history.
if
76 Test a condition. Allows else and elseif clauses.
incr
12 Increment a variable by an integer amount.
info
186 Query the state of the Tcl interpreter.
interp
292 Create additional Tcl interpreters.
join
72 Concatenate list elements with a given separator string.
lappend
66 Add elements to the end of a list.
lindex
68 Fetch an element of a list.
linsert
68 Insert elements into a list.
list
65 Create a list out of the arguments.
llength
68 Return the number of elements in a list.
load
697 Load shared libraries that define Tcl commands.
lrange
68 Return a range of list elements.
lreplace
68 Replace elements of a list.
lsearch
69 Search for an element of a list that matches a pattern.
lset
62 Set an element in a list. (Tcl 8.4)
lsort
70 Sort a list.
namespace
213 Create and manipulate namespaces.
open
116 Open a file or process pipeline for I/O.
package
175 Provide or require code packages.
pid
124 Return the process ID.
Command proc
Pg.
Description
87 Define a Tcl procedure.
puts
119 Output a string to an I/O stream.
pwd
122 Return the current working directory.
read
120 Read blocks of characters from an I/O stream.
regexp
158 Match regular expressions.
regsub
162 Substitute based on regular expressions.
rename
88 Change the name of a Tcl command.
return
86 Return a value from a procedure.
scan
58 Parse a string according to a format specification.
seek set socket
121 Set the seek offset of an I/O stream. 5 Assign a value to a variable. 239 Open a TCP/IP network connection.
source
26 Evaluate the Tcl commands in a file.
split
71 Chop a string up into list elements.
string
49 Operate on strings.
subst switch
140 Substitute embedded commands and variable references. 77 Test several conditions.
tell
121 Return the current seek offset of an I/O stream.
time
202 Measure the execution time of a command.
trace
193 Monitor variable assignments.
unknown
178 Handle unknown commands.
unset uplevel upvar
13 Delete variables. 138 Execute a command in a different scope. 91 Reference a variable in a different scope.
variable
207 Declare namespace variables.
vwait
230 Wait for a variable to be modified.
while [ Team LiB ]
79 Loop until a boolean expression is false.
[ Team LiB ]
Chapter 2. Getting Started UNREGISTERED VERSION OF CHM PDFTkCONVERTER By THETA-SOFTWARE This chapter explains how to run TO Tcl and on different operating system platforms: UNIX, Windows, and Macintosh. Tcl commands discussed are: source, console and info. This chapter explains how to run Tcl scripts on different computer systems. While you can write Tcl scripts that are portable among UNIX, Windows, and Macintosh, the details about getting started are different for each system. If you are looking for a current version of Tcl/Tk, use the UNREGISTERED OF CHM PDF CONVERTER By THETA-SOFTWARE CD-ROM orVERSION check the URLs listedTO in the Preface on page liv. The main Tcl/Tk program is wish. Wish stands for windowing shell, and with it you can create graphical applications that run on all these platforms. The name of the program is a little different on each of the UNIX, Windows, and Macintosh systems. On UNIX it is just wish. On Windows you will find wish.exe, and on the Macintosh the application name is Wish. A version number may also be part of the name, such as wish8.0, wish83.exe, or Wish 8.4. The differences among versions are introduced on page lii, and described in more detail in Part VII of the book. This book will use wish to refer to all of these possibilities. Tk adds Tcl commands that are used to create graphical user interfaces, and Tk is described in Part III. You can run Tcl without Tk if you do not need a graphical interface, such as with the CGI script discussed in Chapter 3. In this case the program is tclsh, tclsh.exe or Tclsh. When you run wish, it displays an empty window and prompts for a Tcl command with a % prompt. You can enter Tcl commands interactively and experiment with the examples in this book. On Windows and Macintosh, a console window is used to prompt for Tcl commands. On UNIX, your terminal window is used. As described later, you can also set up standalone Tcl/Tk scripts that are self-contained applications. [ Team LiB ]
[ Team LiB ]
The source Command It is a good idea to try out the examples in this book as you read along. The highlighted examples from the book are on the CD-ROM in the exsource folder. You can edit these scripts in your favorite editor. Save your examples to a file and then execute them with the Tcl source command:
source filename
The source command reads Tcl commands from a file and evaluates them just as if you had typed them interactively. Chapter 3 develops a sample application. To get started, just open an editor on a file named cgi1.tcl. Each time you update this file you can save it, reload it into Tcl with the source command, and test it again. Development goes quickly because you do not wait for things to compile! [ Team LiB ]
[ Team LiB ]
UNIX Tcl Scripts UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE On UNIX you can create a standalone Tcl or Tcl/Tk script much like an sh or csh script. The trick is in the first line of the file that contains your script. If the first line of a file begins with #!pathname, then UNIX uses pathname as the interpreter for the rest of the script. The "Hello, World!" program from Chapter 1 is repeated in Example 2-1 with the special starting line:
Example 2-1 A standalone Tcl script on UNIX UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE #!/usr/local/bin/tclsh puts stdout {Hello, World!}
The Tk hello world program from Chapter 23 is shown in Example 2-2:
Example 2-2 A standalone Tk script on UNIX #!/usr/local/bin/wish button .hello -text Hello -command {puts "Hello, World!"} pack .hello -padx 10 -pady 10
The actual pathnames for tclsh and wish may be different on your system. If you type the pathname for the interpreter wrong, you receive a confusing "command not found" error. You can find out the complete pathname of the Tcl interpreter with the info nameofexecutable command. This is what appears on my system:
info nameofexecutable => /home/welch/install/linux-ix86/bin/tclsh8.4
Watch out for long pathnames.
On most UNIX systems, this special first line is limited to 32 characters, including the #!. If the pathname is too long, you may end up with /bin/sh trying to interpret your script, giving you syntax errors. You might try using a symbolic link from a short name to the true, long name of the interpreter. However, watch out for systems like older versions of Solaris in which the script interpreter cannot be a symbolic link. Fortunately, Solaris doesn't impose a 32-character limit on the pathname, so you can just use a long pathname.
The next example shows a trick that works around the pathname length limitation in all cases. The trick comes from a posting to comp.lang.tcl by Kevin Kenny. It takes advantage of a difference between comments in Tcl and the Bourne shell. Tcl comments are described on page 16. In the example, the exec Bourne shell command that runs the Tcl interpreter is hidden in a comment as far as Tcl is concerned, but it is visible to /bin/sh. The exec command (in /bin/sh) replaces the current program, so that is all that the Bourne shell processes; Tcl interprets the rest of the script.
Example 2-3 Using /bin/sh to run a Tcl script #!/bin/sh # The backslash makes the next line a comment in Tcl \ exec /some/very/long/path/to/wish "$0" ${1+"$@"} # ... Tcl script goes here ...
You do not even have to know the complete pathname of tclsh or wish to use this trick. You can just do the following:
#!/bin/sh # Run wish from the users PATH \ exec wish -f "$0" ${1+"$@"}
The drawback of an incomplete pathname is that many sites have different versions of wish and tclsh that correspond to different versions of Tcl and Tk. In addition, some users may not have these programs in their PATH. You can hide more than one Bourne shell command in a script with this trick. For example, you might need to set environment variables:
#!/bin/sh # \ export LD_LIBRARY_PATH=/usr/local/lib # \ exec /usr/local/bin/tclsh "$0" ${1+"$@"}
[ Team LiB ]
[ Team LiB ]
Windows Start Menu UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
You can add your Tcl/Tk programs to the Windows start menu. The command is the complete name of the wish.exe program and the name of the script. The trick is that the name of wish.exe has a space in it in the default configuration, so you must use quotes. Your start command will look something like this:
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE "c:\Program Files\Tcl84\wish84.exe" "c:\My Files\script.tcl" This starts c:\My Files\script.tcl as a standalone Tcl/Tk program.
[ Team LiB ]
[ Team LiB ]
Macintosh OS 8/9 and ResEdit If you want to create a self-contained Tcl/Tk application on Macintosh OS 8 or 9, you must copy the Wish program and add a Macintosh resource named tclshrc that has the start-up Tcl code. The Tcl code can be a single source command that reads your script file. Here are step-by-step instructions to create the resource using ResEdit: First, make a copy of Wish and open the copy in ResEdit. Pull down the Resource menu and select Create New Resource operation to make a new TEXT resource. ResEdit opens a window and you can type in text. Type in a source command that names your script: source "Hard Disk:Tcl/Tk 8.3:Applications:MyScript.tcl"
Set the name of the resource to be tclshrc. You do this through the Get Resource Info dialog under the Resources menu in ResEdit. This sequence of commands is captured in an application called Drag n Drop Tclets, which comes with the Macintosh Tcl distribution. If you drag a Tcl script onto this icon, it will create a copy of Wish and create the tclshrc text resource that has a source command that will load that script. If you have a Macintosh development environment, you can build a version of Wish that has additional resources built right in. You add the resources to the applicationInit.r file. If a resource contains Tcl code, you use it like this:
source -rcrc resource
If you don't want to edit resources, you can just use the Wish Source menu to select a script to run.
Macintosh OS X Mac OS X can run the same Tcl/Tk as Macintosh system 8 or 9. However, the preferred version for Mac OS X is Tcl/Tk Aqua, which uses the native windowing system known as Aqua. There are some differences in the application structure due to the new application framework used when building this variant. Wish checks the Resources/Scripts directory in its application bundle for a file called AppMain.tcl, if found it is used as the startup script and the Scripts folder is added to the auto_path. This is similar in spirit to the tclshrc resource described above. Daniel Steffen deserves a great deal of credit for the Tcl/Tk Aqua port and his continued support of the Macintosh platform. He has put together a great distribution that includes many popular extensions, which you can find on the CD-ROM. You can find out more about Tcl/Tk on Macintosh through these URLs:
http://wiki.tcl.tk/macos/ http://www.maths.mq.edu.au/~steffen/tcltk/ [ Team LiB ]
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
[ Team LiB ]
The console Command The Windows and Macintosh platforms have a built-in console that is used to enter Tcl commands interactively. You can control this console with the console command. The console is visible by default. Hide the console like this:
console hide
Display the console like this:
console show
The console is implemented by a second Tcl interpreter. You can evaluate Tcl commands in that interpreter with:
console eval command
There is an alternate version of this console called TkCon. It is included on the CD-ROM, and you can find current versions on the Internet. TkCon was created by Jeff Hobbs and has lots of nice features. You can use TkCon on Unix systems, too. Some of its features were added to console in 8.4. [ Team LiB ]
[ Team LiB ]
Command-Line Arguments UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
If you run a script from the command line, for example from a UNIX shell, you can pass the script command-line arguments. You can also specify these arguments in the shortcut command in Windows. For example, under UNIX you can type this at a shell:
% myscript.tcl arg1 arg2 arg3
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE In Windows, you can have a shortcut that runs wish on your script and also passes additional arguments:
"c:\Program Files\Tcl84\wish.exe" c:\your\script.tcl arg1
The Tcl shells pass the command-line arguments to the script as the value of the argv variable. The number of command-line arguments is given by the argc variable. The name of the program, or script, is not part of argv nor is it counted by argc. Instead, it is put into the argv0 variable. Table 2-2 lists all the predefined variables in the Tcl shells. argv is a list, so you can use the lindex command, which is described on page 63, to extract items from it:
set arg1 [lindex $argv 0]
The following script prints its arguments (foreach is described on page 79):
Example 2-4 The EchoArgs script # Tcl script to echo command line arguments puts "Program: $argv0" puts "Number of arguments: $argc" set i 0 foreach arg $argv { puts "Arg $i: $arg" incr i }
Command-Line Options to Wish Some command-line options are interpreted by wish, and they do not appear in the argv variable. The general form of the wish command line is:
wish ?options? ?script? ?arg1 arg2?
If no script is specified, then wish just enters an interactive command loop. Table 2-1 lists the options that wish supports:
Table 2-1. Wish command line options -colormap new
Use a new private colormap. See page 624.
-display display
Use the specified X display. UNIX only.
-geometry geometry
The size and position of the window. See page 658.
-name name
Specify the Tk application name. See page 648.
-sync
Run X synchronously. UNIX only.
-use id
Use the window specified by id for the main window. See page 667.
-visual visual
Specify the visual for the main window. See page 624.
--
Terminate options to wish.
[ Team LiB ]
[ Team LiB ]
Predefined Variables UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Table 2-2. Variables defined by tclsh and wish argc
The number of command-line arguments.
argv list of the command-line arguments.By THETA-SOFTWARE UNREGISTERED VERSIONA OF CHM TO PDF CONVERTER argv0
The name of the script being executed. If being used interactively, argv0 is the name of the shell program.
embed_args
The list of arguments in the tag. Tcl applets only. See page 314.
env
An array of the environment variables. See page 124.
tcl_interactive True (one) if the tclsh is prompting for commands. tcl_library
The script library directory.
tcl_patchLevel
Modified version number, e.g., 8.0b1.
tcl_platform
Array containing operating system information. See page 192.
tcl_prompt1
If defined, this is a command that outputs the prompt.
tcl_prompt2
If defined, this is a command that outputs the prompt if the current command is not yet complete.
tcl_version
Version number.
auto_path
The search path for script library directories. See page 172.
auto_index
A map from command name to a Tcl command that defines it.
auto_noload
If set, the library facility is disabled.
auto_noexec
If set, the auto execute facility is disabled.
geometry
(wish only). The value of the -geometry argument.
[ Team LiB ]
[ Team LiB ]
Chapter 3. The Guestbook CGI Application This chapter presents a simple Tcl program that computes a Web page. The chapter provides a brief background to HTML and the CGI interface to Web servers. The chapter uses the ncgi package from the standard Tcl library. This chapter presents a complete, but simple, guestbook program that computes an HTML document, or Web page, based on the contents of a simple database. The basic idea is that a user with a Web browser visits a page that is computed by the program. The details of how the page gets from your program to the user with the Web browser vary from system to system. The Tcl Web Server described in Chapter 18 comes with this guestbook example already set up. You can also use these scripts on your own Web server, but you will need help from your Webmaster to set things up. The chapter provides a very brief introduction to HTML and CGI programming. HTML is a way to specify text formatting, including hypertext links to other pages on the World Wide Web. CGI is a standard for communication between a Web server that delivers documents and a program that computes documents for the server. There are many books on these subjects alone. A guestbook is a place for visitors to sign their name and perhaps provide other information. We will build a guestbook that takes advantage of the World Wide Web. Our guests can leave their address as a Universal Resource Location (URL). The guestbook will be presented as a page that has hypertext links to all these URLs so that other guests can visit them. The program works by keeping a simple database of the guests, and it generates the guestbook page from the database. The Tcl scripts described in this chapter use commands and techniques that are described in more detail in later chapters. The goal of the examples is to demonstrate the power of Tcl without explaining every detail. If the examples in this chapter raise questions, you can follow the references to examples in other chapters that do go into more depth. [ Team LiB ]
[ Team LiB ]
A Quick Introduction to HTML UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
Web pages are written in a text markup language called HTML (HyperText Markup Language). The idea of HTML is that you annotate, or mark up, regular text with special tags that indicate structure and formatting. For example, the title of a Web page is defined like this:
My Home Page
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE The tags provide general formatting guidelines, but the browsers that display HTML pages have freedom in how they display things. This keeps the markup simple. The general syntax for HTML tags is:
normal text
As shown here, the tags usually come in pairs. The open tag may have some parameters, and the close tag name begins with a slash. The case of a tag is not considered, so , , and are all valid and mean the same thing. The corresponding close tag could be , , , or even . The tag defines hypertext links that reference other pages on the Web. The hypertext links connect pages into a Web so that you can move from page to page to page and find related information. It is the flexibility of the links that makes the Web so interesting. The tag takes an HREF parameter that defines the destination of the link. If you wanted to link to my home page, you would put this in your page:
Brent Welch
When this construct appears in a Web page, your browser typically displays "Brent Welch" in blue underlined text. When you click on that text, your browser switches to the page at the address "http://www.beedub.com/". There is a lot more to HTML, of course, but this should give you a basic idea of what is going on in the examples. Table 3-1 summarizes the HTML tags that will be used in the examples:
Table 3-1. HTML tags used in the examples
HTML
Main tag that surrounds the whole document.
HEAD
Delimits head section of the HTML document.
TITLE
Defines the title of the page.
BODY
Delimits the body section. Lets you specify page colors.
H1 - H6
HTML defines 6 heading levels: H1, H2, H3, H4, H5, H6.
P
Start a new paragraph.
BR
One blank line.
B
Bold text.
I
Italic text.
A
Used for hypertext links.
IMG
Specify an image.
DL
Definition list.
DT
Term clause in a definition list.
DD
Definition clause in a definition list.
UL
An unordered list.
LI
A bulleted item within a list.
TABLE
Create a table.
TR
A table row.
TD
A cell within a table row.
FORM
Defines a data entry form.
INPUT
A one-line entry field, checkbox, radio button, or submit button.
TEXTAREA A multiline text field. [ Team LiB ]
[ Team LiB ]
CGI for Dynamic Pages UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE
There are two classes of pages on the Web: static and dynamic. A static page is written and stored on a Web server, and the same thing is returned each time a user views the page. This is the easy way to think about Web pages. You have some information to share, so you compose a page and tinker with the HTML tags to get the information to look good. If you have a home page, it is probably in this class.
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE In contrast, a dynamic page is computed each time it is viewed. This is how pages that give upto-the-minute stock prices work, for example. A dynamic page does not mean it includes animations; it just means that a program computes the page contents when a user visits the page. The advantage of this approach is that a user might see something different each time he or she visits the page. As we shall see, it is also easier to maintain information in a database of some sort and generate the HTML formatting for the data with a program. A CGI (Common Gateway Interface) program is used to compute Web pages. The CGI standard defines how inputs are passed to the program as well as a way to identify different types of results, such as images, plain text, or HTML markup. A CGI program simply writes the contents of the document to its standard output, and the Web server takes care of delivering the document to the user's Web browser. Example 3-1 is a very simple CGI script:
Example 3-1 A simple CGI script puts puts puts puts
"Content-Type: text/html" "" "The Current Time " "The time is [clock format [clock seconds]] "
The program computes a simple HTML page that has the current time. Each time a user visits the page, she will see the current time on the server. The server that has the CGI program and the user viewing the page might be on different sides of the planet. The output of the program is divided into two sections: the protocol header and the page contents. In this simple example, the protocol header just has a Content-Type line that tells your Web browser what kind of data comes next. A blank line separates the protocol header from the page, which starts with a tag, in this case. The clock command is used twice: once to get the current time in seconds, and a second time to format the time into a nice-looking string. The clock command is described in detail on page 183. Fortunately, there is no conflict between the markup syntax used by HTML and the Tcl syntax for embedded commands, so we can mix the two in the argument to the puts command. Double quotes are used to group the argument to puts so that the clock command will be executed. Example 3-2 shows what the output of the program will look like:
Example 3-2 Output of Example 3-1 Content-Type: text/html
The Current Time The time is Wed Jul 10 14:29:36 2002
This example is a bit sloppy in its use of HTML, but it should display properly in most Web browsers. Example 3-3 includes all the required tags for a proper HTML document. [ Team LiB ]
[ Team LiB ]
The guestbook.cgi Script UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE The guestbook.cgi script computes a page that lists all the registered guests. Example 3-3 is shown first, and then each part of it is discussed in more detail later. One thing to note right away is that the HTML tags are generated by procedures that hide the details of the HTML syntax. The first lines of the script use the UNIX trick to have tclsh interpret the script. This is described on page 26:
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Example 3-3 The guestbook.cgi script, version 1 #!/bin/sh # guestbook.cgi # Implement a simple guestbook page. # The set of visitors is kept in a simple database. # The newguest.cgi script will update the database. # \ exec tclsh "$0" ${1+"$@"} # The guestbook.data file has the database # The datafile is in the same directory as the script set dir [file dirname [info script]] set datafile [file join $dir guestbook.data] puts "text/html" puts "" set title "Brent's Guestbook" puts "$title " puts " " puts "$title " if {![file exists $datafile]} { puts "No registered guests, yet. Be the first registered guest! " } else { puts "The following folks have registered in my GuestBook.
Register
Guests " catch {source $datafile} foreach name [lsort [array names Guestbook]] { set item $Guestbook($name) set homepage [lindex $item 0] set markup [lindex $item 1] puts "" puts $markup }
} puts ""
Using a Script Library File If you write one CGI script, you are likely to write several. You could start making copies and modifying your first script, but that quickly becomes hard to maintain. If you learn something new after writing your third script, will you remember to update the first two scripts you wrote? Probably not. The best way to approach this problem is to create a collection of Tcl procedures in a file that you share among all your CGI scripts. The Standard Tcl Library, tcllib, provides several packages of procedures that you can use. Later in this chapter, we will look at the ncgi package that helps handle form data. Before we do that, let's start a simple collection of our own procedures and learn how to share them among several different CGI scripts. Suppose you have a file cgihacks.tcl that contains your Tcl procedures. The source command loads that file into your script. The naive approach shown here probably won't work:
source cgihacks.tcl
Loading a file from the same directory as your script
The problem is that the current directory of the CGI process may not be the same as the directory that contains the CGI script or the cgihacks.tcl file. You can use the info script command to find out where the CGI script is, and from that load the supporting file. The file dirname and file join commands manipulate file names in a platform-independent way. They are described on page 108. I use the following trick to avoid putting absolute file names into my scripts, which would have to be changed if the program moves later:
set dir [file dirname [info script]] source [file join $dir cgihacks.tcl]
You can also create script libraries as described in Chapter 12. That chapter describes tools to create an index of procedures so an application can quickly load the procedures it needs, and how to create packages of procedures so you can keep your code organized. However you set them up, it is always a good idea to have a library of procedures you share with other applications.
Beginning the HTML Page
The way you start your HTML page is a great candidate for capturing in a Tcl procedure. For example, I like to have the page title appear in the TITLE tag in the head, and repeated in an H1 tag at the beginning of the body. You may also have a favorite set of colors or fonts that you want to specify in the BODY tag. By putting all this into a Tcl procedure, you can make it easy to share this among all your scripts. If your tastes change tomorrow, then you can change the Tcl procedure in one spot and affect all CGI scripts that share the procedure. Example 3-4 shows Cgi_Header that generates a simple standard page header:
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE Example 3-4 The Cgi_Header procedure proc Cgi_Header {title {body {bgcolor=white text=black}}} { puts stdout "Content-Type: text/html
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE $title $title " }
The Cgi_Header procedure takes as arguments the title for the page and some optional parameters for the HTML BODY tag. The procedure definition uses the syntax for an optional parameter, so you do not have to pass bodyparams to Cgi_Header. The default specifies black text on a white background to avoid the standard gray background of most browsers. Default values for procedure parameters are described on page 87.
Example 3-5 The guestbook.cgi script, version 2 #!/bin/sh # guestbook.cgi # Implement a simple guestbook page. # The set of visitors is kept in a simple database. # The newguest.cgi script will update the database. # \ exec tclsh "$0" ${1+"$@"} # The guestbook.data file has the database # The datafile is in the same directory as the script set dir [file dirname [info script]] set datafile [file join $dir guestbook.data] # Load our supporting Tcl procedures to define Cgi_Header source [file join $dir cgihacks.tcl] Cgi_Header "Brent's Guestbook" if {![file exists $datafile]} { puts "No registered guests, yet. Be the first
registered guest! " } else { puts "The following folks have registered in my GuestBook.
Register
Guests " catch {source $datafile} foreach name [lsort [array names Guestbook]] { set item $Guestbook($name) set homepage [lindex $item 0] set markup [lindex $item 1] puts "" puts $markup } } puts ""
Example 3-5 is a new version of the original CGI script that loads the cgihacks.tcl file and uses Cgi_Header. The Cgi_Header procedure just contains a single puts command that generates the standard boilerplate that appears at the beginning of the output. Note that several lines are grouped together with double quotes. Double quotes are used so that the variable references mixed into the HTML are substituted properly. The output of the Cgi_Header procedure matches what we wrote by hand in Example 3-3.
Sample Output of the CGI Script The program tests to see whether there are any registered guests or not. The file command, which is described in detail on page 108, is used to see whether there is any data. The exclamation point means "not" in a boolean expression:
if {![file exists $datafile]} {
If the database file does not exist, a different page is displayed to encourage a registration. The page includes a hypertext link to a registration page, newguest.html, which is described on page 43. The output of the program would be as below in Example 3-6 if there were no data file:
Example 3-6 Initial output of guestbook.cgi with no data Content-Type: text/html Brent's Guestbook Brent's Guestbook No registered guests.
Be the first registered guest!
Note the inconsistent indentation of the HTML that comes from the indentation in the puts command used for that part of the page. The browser doesn't care about white space in the HTML. You have a choice between lining up the Tcl commands in your CGI script, or lining up UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE the HTML output. Here we have two different examples. The Cgi_Header procedure produces output that is lined up, but the procedure definition looks a bit odd. The main script, in contrast, keeps its Tcl commands neatly indented, but that shows up in the output. If you generate most of your HTML from code, you may choose to keep your code tidy. Example 3-7 shows the output of the guestbook.cgi script when there is some data in the
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE data file:
Example 3-7 Output of guestbook.cgi with guestbook data Content-Type: text/html
Brent's Guestbook Brent's Guestbook The following folks have registered in my guestbook.
Register
Guests
Using a Tcl Array for the Database The data file contains Tcl commands that define an array that holds the guestbook data. If this file is kept in the same directory as the guestbook.cgi script, then you can compute its name:
set dir [file dirname [info script]] set datafile [file join $dir guestbook.data]
By using Tcl commands to represent the data, we can load the data with the source command. The catch command is used to protect the script from a bad data file, which will show up as an error from the source command. Catching errors is described in detail on page 85:
catch {source $datafile}
The Guestbook variable is the array defined in guestbook.data. Array variables are the topic of Chapter 8. Each element of the array is defined with a Tcl command that looks like this:
set Guestbook(key) {url markup}
The person's name is the array index, or key. The value of the array element is a Tcl list with two elements: their URL and some additional HTML markup that they can include in the guestbook. Tcl lists are the topic of Chapter 5. The following example shows what the command looks like with real data:
set {Guestbook(Brent Welch)} { http://www.beedub.com/ { } }
The spaces in the name result in additional braces to group the whole variable name and each list element. This syntax is explained on page 96. Do not worry about it now. We will see on page 46 that all the braces in the previous statement are generated automatically. The main point is that the person's name is the key, and the value is a list with two elements. The array names command returns all the indices, or keys, in the array, and the lsort command sorts these alphabetically. The foreach command loops over the sorted list, setting the loop variable x to each key in turn:
foreach name [lsort [array names Guestbook]] {
The lsort command will sort the names based on the person's first name. You can have lsort sort things in a variety of ways. One trick we can use here is to have lsort treat each key as a list and sort on the last item in the list (i.e., the last name):
foreach name [lsort -index end [array names Guestbook]] {
The lsort command is described in more detail on page 70. The foreach command assigns name to each key of the Guestbook array. We get the value like this:
set item $Guestbook($name)
The two list elements are extracted with lindex, which is described on page 68.
set homepage [lindex $item 0] set markup [lindex $item 1]
We generate the HTML for the guestbook entry as a level-three header that contains a hypertext link to the guest's home page. We follow the link with any HTML markup text that the guest has supplied to embellish his or her entry:
puts "" puts $markup
The homepage and markup variables are not strictly necessary, and the code could be written more compactly without them. However, the variables make the code more understandable. Here is what it looks like without the temporary variables:
UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE puts "" puts [lindex $item 1]
UNREGISTERED OF CHM TO PDF CONVERTER By THETA-SOFTWARE [ Team LiBVERSION ]
[ Team LiB ]
Defining Forms and Processing Form Data The guestbook.cgi script only generates output. The other half of CGI deals with input from the user. Input is more complex for two reasons. First, we have to define another HTML page that has a form for the user to fill out. Second, the data from the form is organized and encoded in a standard form that must be decoded by the script. Example 3-8 on page 43 defines a very simple form, and the procedure that decodes the form data is shown in Example 11-6 on page 165. The guestbook page contains a link to newguest.html . This page contains a form that lets a user register his or her name, home page URL, and some additional HTML markup. The form has a submit button. When a user clicks that button in her browser, the information from the form is passed to the newguest.cgi script. This script updates the database and computes another page for the user that acknowledges the user's contribution.
The newguest.html Form An HTML form contains tags that define data entry fields, buttons, checkboxes, and other elements that let the user specify values. For example, a one-line entry field that is used to enter the home page URL is defined like this:
The INPUT tag is used to define several kinds of input elements, and its type parameter indicates what kind. In this case, TYPE=text creates a one-line text entry field. The submit button is defined with an INPUT tag that has TYPE=submit , and the VALUE parameter becomes the text that appears on the submit button:
A general type-in window is defined with the TEXTAREA tag. This creates a multiline, scrolling text field that is useful for specifying lots of information, such as a free-form comment. In our case, we will let guests type in HTML that will appear with their guestbook entry. The text between the open and close TEXT-AREA tags is inserted into the type-in window when the page is first displayed.
A common parameter to the form tags is NAME= something . This name identifies the data that will come back from the form. The tags also have parameters that affect their display, such as the label on the submit button and the size of the text area. Those details are not important for our example. The complete form is shown in Example 3-8 :
Example 3-8 The newguest.html form
Register in my Guestbook
The ncgi and cgi.tcl Packages The newguest.cgi script uses the ncgi package to process form data. This is one of many packages available in the Standard Tcl Library, commonly known as "tcllib". If you don't have tcllib installed, you can find it on the CD-ROM, on SourceForge at www.sf.net/projects/tcllib , or via the main www.tcl.tk Web site. If your Tcl installation includes tcllib, then you use the package command to load the package.
package require ncgi
The procedures in the ncgi package are in the ncgi namespace. Tcl namespaces are described in detail in Chapter 14 . Procedures in a namespace are qualified with the name of the namespace and :: syntax. For example, the standard setup procedure for a CGI script is ncgi::parse . The "n" in ncgi is for "new". Don Libes wrote the original package for CGI scripts known as cgi.tcl . There is also the cgilib.tcl package that contains Cgi_Header and some other procedures described in earlier editions of this book. The ncgi and html packages of tcllib provide most of the features in both cgi.tcl and cgilib.tcl , but follow the standard namespace conventions use by the packages in tcllib. You can still find cgi.tcl on the Web at http://expect.nist.gov/cgi.tcl/
The newguest.cgi Script When the user clicks the Submit button in her browser, the data from the form is passed to the program identified by the ACTION parameter of the form tag. That program takes the data, does
something useful with it, and then returns a new page for the browser to display. In our case, the FORM tag names newguest.cgi as the program to handle the data:
The CGI specification defines how the data from the form is passed to the program. The data is encoded and organized so that the program can figure out the values the user specified for each form element. The encoding is handled rather nicely with some regular expression tricks that are done in ncgi::parse . ncgi::parse saves the form data, and ncgi::value gets a form value in the script. These procedures are described in Example 11-6 on page 165. Example 3-9 starts out by calling ncgi::parse :
Example 3-9 The newguest.cgi script #!/bin/sh # \ exec tclsh "$0" ${1+"$@"} # Use the ncgi package from tcllib to process form data package require ncgi ncgi::parse # Load our data file and supporting procedures set dir [file dirname [info script]] set datafile [file join $dir guestbook.data] source [file join $dir cgihacks.tcl] # Open the datafile in append mode if {[catch {open $datafile a} out]} { Cgi_Header "Guestbook Registration Error" \ {BGCOLOR=black TEXT=red} puts "Cannot open the data file
" puts $out;# the error message exit 0 } # Append a Tcl set command that defines the guest's entry puts $out "" puts $out [list set Guestbook([ncgi::value name]) \ [list [ncgi::value url] [ncgi::value html]]] close $out # Return a page to the browser Cgi_Header "Guestbook Registration Confirmed" \ {BGCOLOR=white TEXT=black} puts "
" UNREGISTERED VERSION OF CHM TO PDF CONVERTER By THETA-SOFTWARE puts