practical programming in tcl and tk

1207
Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch Publisher: Prentice Hall PTR Pub Date: November 10, 1999 ISBN: 0-13-022028-0 Pages: 832 Supplier: Team FLY Tcl/Tk 8.2 is the first scripting language that can handle enterprise-wide integration tasks that encompass Windows, Solaris, Macintosh, and other key platforms. Now, in this fully updated Third Edition, Tcl/Tk development team member and best-selling author Brent Welch presents all you need to know to achieve powerful results with Tcl/Tk 8.2 and the new Tcl Web Server. Coverage includes: Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch Publisher: Prentice Hall PTR Pub Date: November 10, 1999 ISBN: 0-13-022028-0 Pages: 832 Supplier: Team FLY Tcl/Tk 8.2 is the first scripting language that can handle enterprise-wide integration tasks that encompass Windows, Solaris, Macintosh, and other key platforms. Now, in this fully updated Third Edition, Tcl/Tk development team member and best-selling author Brent Welch presents all you need to know to achieve powerful results with Tcl/Tk 8.2 and the new Tcl Web Server. Coverage includes:

Upload: gunitle

Post on 27-Nov-2014

306 views

Category:

Documents


46 download

TRANSCRIPT

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Publisher: Prentice Hall PTR Pub Date: November 10, 1999 ISBN: 0-13-022028-0 Pages: 832 Supplier: Team FLY

Tcl/Tk 8.2 is the first scripting language that can handle enterprise-wide integration tasks that encompass Windows, Solaris, Macintosh, and other key platforms. Now, in this fully updated Third Edition, Tcl/Tk development team member and best-selling author Brent Welch presents all you need to know to achieve powerful results with Tcl/Tk 8.2 and the new Tcl Web Server. Coverage includes:

Tcl's fundamental mechanisms and operating system interfaces Basic and advanced coding techniques and tools, including the Tcl script library facility Tk and X Windows-with detailed examples and sample widgets The new, extensible Tcl Web Server New Tcl internationalization features and thread support New techniques for working with regular expressions and namespaces You'll find extensive coverage of user interface development, as well as application integration techniques that leverage Tcl/Tk's powerful cross-platform scripting capabilities. Welch covers Tcl's extensive network support, as well as Safe Tcl, C programming with the Tk toolkit, the Tcl compiler, and Tcl/Tk plug-ins for Netscape and Internet Explorer. Whether you're a current Tcl/Tk programmer, or a developer searching for a convenient, powerful multiplatform scripting language, Practical Programming in Tcl and Tk, Third Edition delivers exactly what you're looking for. "This is an excellent book, loaded with useful examples. Newcomers to Tk will find the widget descriptions particularly helpful." -John Ousterhout CEO and founder of Scriptics Corporation and the creator of Tcl/Tk "Brent Welch fills an important need for an introduction to Tcl/Tk with an applied focus and with coverage of many of the useful extensions available . . . I recommend this book to my new students . . . and I keep a copy handy for my own use." -Joseph A. Konstan, Professor of Computer Science University of Minnesota

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Publisher: Prentice Hall PTR Pub Date: November 10, 1999 ISBN: 0-13-022028-0 Pages: 832 Supplier: Team FLY

Copyright List of Examples List of Tables Preface Why Tcl? Tcl and Tk Versions Who Should Read This Book How to Read This Book Other Tcl Books On-line Examples Ftp Archives World Wide Web Newsgroups Typographic Conventions Hot Tips Book Organization What's New in the Third Edition First Edition Thanks Second Edition Thanks Third 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 95 Start Menu The Macintosh 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 The cgi.tcl Package Next Steps Chapter 4. String Processing in Tcl The string Command The append Command The format Command The scan Command The binary Command Related Chapters Chapter 5. Tcl Lists Tcl Lists Constructing Lists Getting List Elements: llength, lindex, and lrange Modifying Lists: linsert and lreplace Searching Lists: lsearch Sorting Lists: lsort The split Command The join Command Related Chapters Chapter 6. Control Structure CommandsIf Then Else Switch While Foreach For Break Catch Error Return

and Continue

Chapter 7. Procedures and Scope The proc Command Changing Command Names with rename Scope The global Command Call by Name Using upvar Variable Aliases with upvar Chapter 8. Tcl Arrays Array Syntax The array Command Building Data Structures with Arrays Chapter 9. Working with Files and Programs Running Programs with exec The file Command Cross-Platform File Naming Manipulating Files and Directories File Attributes Input/Output Command Summary Opening Files for I/O Reading and Writing The Current Directory ?cd and pwd Matching File Names with glob The exit and pid Commands Environment Variables The registry Command Part II. Advanced Tcl Chapter 10. Quoting Issues and Eval Constructing Code with the list Command Exploiting the concat inside eval The uplevel Command The subst Command Chapter 11. Regular Expressions When to Use Regular Expressions Regular Expression Syntax Advanced Regular Expressions Syntax Summary The regexp Command The regsub 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 tclIndex File

The unknown Command Interactive Conveniences Tcl Shell Library Environment Coding Style Chapter 13. Reflection and Debugging The clock Command The info Command Cross-Platform Support Tracing Variable Values Interactive Command History Debugging Scriptics' TclPro 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

Notes Chapter 15. Internationalization Character Sets and Encodings Message Catalogs Chapter 16. Event-Driven Programming The Tcl Event Loop The after Command The fileevent Command The vwait Command The fconfigure Command Chapter 17. Socket Programming Client Sockets Server Sockets The Echo Service Fetching a URL with HTTP 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 Part III. Tk Basics Chapter 21. Tk Fundamentals Hello, World! in Tk Naming Tk Widgets Configuring Tk Widgets Tk Widget Attributes and the Resource Database Summary of the Tk Commands Chapter 22. Tk by Example ExecLog The Example Browser A Tcl Shell Chapter 23. 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 24. The Grid Geometry Manager

A Basic Grid Spanning Rows and Columns Row and Column Constraints The grid Command Chapter 25. The Place Geometry Manageryplace

Basics

The Pane Manager The place Command Chapter 26. Binding Commands to Events The bind Command The bindtags Command Event Syntax Modifiers Event Sequences Virtual Events Event Keywords Part IV. Tk Widgets Chapter 27. Buttons and Menus Button Commands and Scope Issues Buttons Associated with Tcl Variables Button Attributes Button Operations Menus and Menubuttons Keyboard Traversal Manipulating Menus and Menu Entries Menu Attributes A Menu by Name Package Chapter 28. 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 29. Simple Tk Widgets Frames and Toplevel Windows The Label Widget The Message Widget The Scale Widget The bell Command Chapter 30. Scrollbars Using Scrollbars The Scrollbar Protocol The Scrollbar Widget Chapter 31. The Entry Widget Using Entry Widgets

The Entry Widget Chapter 32. The Listbox Widget Using Listboxes Listbox Bindings Listbox Attributes Chapter 33. The Text Widget Text Indices Text Marks Text Tags The Selection Tag Bindings Searching Text Embedded Widgets Embedded Images Looking inside the Text Widget Text Bindings Text Operations Text Attributes Chapter 34. 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 35. Selections and the Clipboard The Selection Model The selection Command The clipboard Command Selection Handlers Chapter 36. Focus, Grabs, and Dialogs Standard Dialogs Custom Dialogs Animation with the update Command Chapter 37. Tk Widget Attributes Configuring Attributes Size Borders and Relief The Focus Highlight Padding and Anchors Chapter 38. Color, Images, and Cursors Colors Colormaps and Visuals

Bitmaps and Images The Text Insert Cursor The Mouse Cursor Chapter 39. 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 40. Send The send Command The Sender Script Communicating Processes Remote eval through Sockets Chapter 41. Window Managers and Window Information The wm Command The winfo Command The tk Command Chapter 42. 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 43. A User Interface to Bindings A Pair of Listboxes Working Together The Editing Interface Saving and Loading Bindings Part VI. C Programming Chapter 44. C Programming and Tcl Basic Concepts Creating a Loadable Package A C Command Procedure The blob Command Example Strings and InternationalizationTcl_Main

and Tcl_AppInit

The Event Loop Invoking Scripts from C Chapter 45. Compiling Tcl and Extensions Standard Directory Structure Building Tcl from Source Using Stub Libraries Using autoconf

The Sample Extension Chapter 46. 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 47. C Library Overview An Overview of the Tcl C Library An Overview of the Tk C Library Part VII. Changes Chapter 48. Tcl 7.4/Tk 4.0 wish Obsolete Features The cget Operation Input Focus Highlight Bindings Scrollbar Interfacepack info

Focus The send Command Internal Button Padding Radiobutton Value Entry Widget Menus Listboxes No geometry Attribute Text Widget Color Attributes Color Allocation and tk colormodel Canvas scrollincrement The Selection The bell Command Chapter 49. Tcl 7.5/Tk 4.1 Cross-Platform Scripts The clock Command The load Command The package Command Multiple foreach loop variables 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 50. Tcl 7.6/Tk 4.2 More file Operations Virtual Events Standard Dialogs New grid Geometry Manager Macintosh unsupported1 Command Chapter 51. Tcl/Tk 8.0 The Tcl Compiler Namespaces Safe-Tcl New lsorttcl_precision

Variable

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 No Errors from destroygrid rowconfigure

The Patch Releases Chapter 52. Tcl/Tk 8.1 Unicode and Internationalization Thread Safety Advanced Regular Expressions New String Commands The DDE Extension Miscellaneous Chapter 53. Tcl/Tk 8.2 The Trf Patch Faster String Operations Empty Array Names Brower Plugin Compatiblity Chapter 54. Tcl/Tk 8.3 Proposed Tcl Changes Proposed Tk Changes Chapter 55. About The CD-ROM Technical Support Index

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

CopyrightLibrary of Congress Cataloging-in-Publication Data Welch, Brent. B. Practical programming in Tcl and Tk / Brent B. Welch.-- 3rd ed. p. cm. ISBN 0-13-022028-0 1. Tcl (Computer program language) 2. Tk toolkit. I. Title. QA76.73.T44 W45 1999 005.13'3--dc21 99-047206

CreditsEditorial/Production Supervision: Joan L. McNamara Acquisitions Editor: Mark Taub Marketing Manager: Kate Hargett Editorial Assistant: Michael Fredette Cover Design Director: Jerry Votta Cover Design: Design Source Manufacturing Manager: Alexis R. Heydt 2000, 1997 by Prentice Hall PTR Prentice-Hall, Inc. Upper Saddle River, New Jersey 07458

Prentice Hall books are widely used by corporations and government agencies for training, marketing, and resale. The publisher offers discounts on this book when ordered in bulk quantities. For more information, contact: Corporate Sales Department, Prentice Hall PTR, One Lake Street, Upper Saddle River, NJ 07458 Phone: 800-382-3419; Fax: 201-236-7141; email: [email protected] 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. All product names mentioned herein are the trademarks of their respective owners. Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 Prentice-Hall International (UK) Limited, London Prentice-Hall of Australia Pty. Limited, Sydney Prentice-Hall Canada Inc., Toronto Prentice-Hall Hispanoamericana, S.A., Mexico Prentice-Hall of India Private Limited, New Delhi Prentice-Hall of Japan, Inc., Tokyo Prentice-Hall (Singapore) Pte. Ltd., Singapore Editora Prentice-Hall do Brasil, Ltda., Rio de Janeiro

Dedicationto Jody, Christopher, Daniel, and Michael

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

List of Examples1.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.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.1 A simple CGI script 3.2 Output of Example 3-1 3.3 The guestbook.cgi script 3.4 The Cgi_Header procedure 3.5 The Link command formats a hypertext link 3.6 Initial output of guestbook.cgi 3.7 Output of guestbook.cgi 3.8 The newguest.html form 3.9 The newguest.cgi script 4.1 Comparing strings with string compare 4.2 Comparing strings with string equal 4.3 Mapping Microsoft World special characters to ASCII 5.1 Constructing a list with the list command 5.2 Using lappend to add elements to a list 5.3 Using concat to splice lists together 5.4 Double quotes compared to the concat and list commands 5.5 Modifying lists with linsert and lreplace 5.6 Deleting a list element by value 5.7 Sorting a list using a comparison function 5.8 Use split to turn input data into Tcl lists 5.9 Implementing join in Tcl 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.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.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 a list to implement a stack

8.8 Using an array to implement a stack 8.9 A list of arrays 8.10 A list of arrays 8.11 A simple in-memory database 9.1 Using exec on a process pipeline 9.2 Comparing file modify times 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.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 applies a command to each line of a file 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_Parse and Cgi_Value procedures 11.7 Cgi_Parse and Cgi_Value store query data in the cgi array

11.8 Html_DecodeEntity 11.9 Html_Parse 12.1 Maintaining a tclIndex file 12.2 Loading a tclIndex file 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.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.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.1 A read event file handler 16.2 Using vwait to activate the event loop

16.3 A read event file handler for a nonblocking channel 17.1 Opening a client socket with a timeout 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 to an HTTP server 17.7 Http_Head validates a URL 17.8 Using Http_Head 17.9 Http_Get fetches the contents of a URL 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.1 A simple URL domain 18.2 Application Direct URLs 18.3 Alternate types for Application Direct URLs 18.4 A sample document type handler 18.5 A one-level site structure 18.6 A HTML + Tcl template file 18.7 SitePage template procedure 18.8 SiteMenu and SiteFooter template procedures 18.9 The SiteLink procedure 18.10 Mail form results with /mail/forminfo 18.11 Mail message sent by /mail/forminfo 18.12 Processing mail sent by /mail/forminfo 18.13 A self-checking form procedure

18.14 A page with a self-checking form 18.15 The /debug/source application-direct URL implementation 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 21.1 "Hello, World!" Tk program. 21.2 Looking at all widget attributes 22.1 Logging the output of a program run with exec 22.2 A platform-specific cancel event 22.3 A browser for the code examples in the book 22.4 A Tcl shell in a text widget 22.5 Macintosh look and feel 22.6 Windows look and feel 22.7 UNIX look and feel 23.1 Two frames packed inside the main frame 23.2 Turning off geometry propagation 23.3 A horizontal stack inside a vertical stack 23.4 Even more nesting of horizontal and vertical stacks 23.5 Mixing bottom and right packing sides 23.6 Filling the display into extra packing space

23.7 Using horizontal fill in a menu bar 23.8 The effects of internal padding (-ipady) 23.9 Button padding vs. packer padding 23.10 The look of a default button 23.11 Resizing without the expand option 23.12 Resizing with expand turned on 23.13 More than one expanding widget 23.14 Setup for anchor experiments 23.15 The effects of noncenter anchors 23.16 Animating the packing anchors 23.17 Controlling the packing order 23.18 Packing into other relatives 24.1 A basic grid 24.2 A grid with sticky settings 24.3 A grid with row and column specifications 24.4 A grid with external padding 24.5 A grid with internal padding 24.6 All combinations of -sticky settings 24.7 Explicit row and column span 24.8 Grid syntax row and column span 24.9 Row padding compared to widget padding 24.10 Gridding a text widget and scrollbar 25.1 Centering a window with place 25.2 Covering a window with place 25.3 Combining relative and absolute sizes 25.4 Positioning a window above a sibling with place 25.5 Pane_Create sets up vertical or horizontal panes 25.6 PaneDrag adjusts the percentage

25.7 PaneGeometry updates the layout 26.1 Bindings on different binding tags 26.2 Output from the UNIX xmodmap program 26.3 Emacs-like binding convention for Meta and Escape 26.4 Virtual events for cut, copy, and paste 27.1 A troublesome button command 27.2 Fixing the troublesome situation 27.3 A button associated with a Tcl procedure 27.4 Radiobuttons and checkbuttons 27.5 A command on a radiobutton or checkbutton 27.6 A menu sampler 27.7 A menu bar in Tk 8.0 27.8 A simple menu by name package 27.9 Using the Tk 8.0 menu bar facility 27.10 MenuGet maps from name to menu 27.11 Adding menu entries 27.12 A wrapper for cascade entries 27.13 Using the menu by name package 27.14 Keeping the accelerator display up to date 28.1 Reading an option database file 28.2 A file containing resource specifications 28.3 Using resources to specify user-defined buttons 28.4 Resource_ButtonFrame defines buttons based on resources 28.5 Using Resource_ButtonFrame 28.6 Specifying menu entries via resources 28.7 Defining menus from resource specifications 28.8 Resource_GetFamily merges user and application resources 29.1 Macintosh window styles

29.2 A label that displays different strings 29.3 The message widget formats long lines of text 29.4 Controlling the text layout in a message widget 29.5 A scale widget 30.1 A text widget and two scrollbars 30.2 Scroll_Set manages optional scrollbars 30.3 Listbox with optional scrollbars 31.1 A command entry 32.1 Choosing items from a listbox 33.1 Tag configurations for basic character styles 33.2 Line spacing and justification in the text widget 33.3 An active text button 33.4 Delayed creation of embedded widgets 33.5 Using embedded images for a bulleted list 33.6 Finding the current range of a text tag 33.7 Dumping the text widget 33.8 Dumping the text widget with a command callback 34.1 A large scrolling canvas 34.2 The canvas "Hello, World!" example 34.3 A min max scale canvas example 34.4 Moving the markers for the min max scale 34.5 Canvas arc items 34.6 Canvas bitmap items 34.7 Canvas image items 34.8 A canvas stroke drawing example 34.9 Canvas oval items 34.10 Canvas polygon items 34.11 Dragging out a box

34.12 Simple edit bindings for canvas text items 34.13 Using a canvas to scroll a set of widgets 34.14 Generating postscript from a canvas 35.1 Paste the PRIMARY or CLIPBOARD selection 35.2 Separate paste actions 35.3 Bindings for canvas selection 35.4 Selecting objects 35.5 A canvas selection handler 35.6 The copy and cut operations 35.7 Pasting onto the canvas 36.1 Procedures to help build dialogs 36.2 A simple dialog 36.3 A feedback procedure 37.1 Equal-sized labels 37.2 3D relief sampler 37.3 Padding provided by labels and buttons 37.4 Anchoring text in a label or button 37.5 Borders and padding 38.1 Resources for reverse video 38.2 Computing a darker color 38.3 Specifying an image for a widget 38.4 Specifying a bitmap for a widget 38.5 The built-in bitmaps 38.6 The Tk cursors 39.1 The FontWidget procedure handles missing fonts 39.2 Font metrics 39.3 A gridded, resizable listbox

39.4 Font selection dialog 40.1 The sender application 40.2 Hooking the browser to an eval server 40.3 Making the shell into an eval server 40.4 Remote eval using sockets 40.5 Reading commands from a socket 40.6 The client side of remote evaluation 41.1 Gridded geometry for a canvas 41.2 Telling other applications what your name is 42.1 Preferences initialization 42.2 Adding preference items 42.3 Setting preference variables 42.4 Using the preferences package 42.5 A user interface to the preference items 42.6 Interface objects for different preference types 42.7 Displaying the help text for an item 42.8 Saving preferences settings to a file 42.9 Read settings from the preferences file 42.10 Tracing a Tcl variable in a preference item 43.1 A user interface to widget bindings 43.2 Bind_Display presents the bindings for a widget or class 43.3 Related listboxes are configured to select items together 43.4 Controlling a pair of listboxes with one scrollbar 43.5 Drag-scrolling a pair of listboxes together 43.6 An interface to define bindings 43.7 Defining and saving bindings 44.1 The initialization procedure for a loadable package 44.2 The RandomCmd C command procedure

44.3 The RandomObjCmd C command procedure 44.4 The Tcl_Obj structure 44.5 The Plus1ObjCmd procedure 44.6 The Blob and BlobState data structures 44.7 The Blob_Init and BlobCleanup procedures 44.8 The BlobCmd command procedure 44.9 BlobCreate and BlobDelete 44.10 The BlobNames procedure 44.11 The BlobN and BlobData procedures 44.12 The BlobCommand and BlobPoke procedures 44.13 A canonical Tcl main program and Tcl_AppInit 44.14 A canonical Tk main program and Tk_AppInit 44.15 Calling C command procedure directly with Tcl_Invoke 46.1 The Clock_Init procedure 46.2 The Clock widget data structure 46.3 The ClockCmd command procedure 46.4 The ClockObjCmd command procedure 46.5 The ClockInstanceCmd command procedure 46.6 The ClockInstanceObjCmd command procedure 46.7 ClockConfigure allocates resources for the widget 46.8 ClockObjConfigure allocates resources for the widget 46.9 The Tk_ConfigSpec typedef 46.10 Configuration specs for the clock widget 46.11 The Tk_OptionSpec typedef 46.12 The Tk_OptionSpec structure for the clock widget 46.13 ComputeGeometry computes the widget's size 46.14 The ClockDisplay procedure 46.15 The ClockEventPro handles window events

46.16 The ClockDestroy cleanup procedure 46.17 The ClockObjDelete command

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

List of Tables1-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-1 Wish command line options 2-2 Variables defined by tclsh and wish 3-1 HTML tags used in the examples 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-1 List-related commands 8-1 The array command 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 9-8 The registry command 9-9 The registry data types 11-1 Basic regular expression syntax 11-2 Additional advanced regular expression syntax 11-3 Character classes 11-4 Backslash escapes in regular expressions 11-5 Embedded option characters used with the (?x) syntax 11-6 Options to the regexp command 11-7 Sample regular expressions 12-1 Options to the pkg_mkIndex command 12-2 The package command 13-1 The clock command 13-2 Clock formatting keywords 13-3 UNIX-specific clock formatting keywords 13-4 The info command 13-5 The history command 13-6 Special history syntax 14-1 The namespace command 15-1 The encoding command 15-2 The msgcat package 16-1 The after command 16-2 The fileevent command 16-3 I/O channel properties controlled by fconfigure 16-4 End of line translation modes 17-1 Options to the http::geturl command

17-2 Elements of the http::geturl state array 17-3 The http support procedures 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 The form package 18-7 Elements of the page array 18-8 Elements of the env array 18-9 Status application-direct URLs 18-10 Debug application-direct URLs 18-11 Application-direct URLS that e-mail form results 18-12 Basic TclHttpd Parameters 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-1 Tk commands omitted from safe interpreters 20-2 Plugin Environment Variables 20-3 Aliases defined by the browser package 20-4 The browser::getURL callbacks 21-1 Tk widget-creation commands 21-2 Tk widget-manipulation commands 21-3 Tk support procedures 23-1 The pack command 23-2 Packing options 24-1 The grid command

24-2 Grid widget options 25-1 The place command 25-2 Placement options 26-1 Event types 26-2 Event modifiers 26-3 The event command 26-4 A summary of the event keywords 27-1 Resource names of attributes for all button widgets 27-2 Button operations 27-3 Menu entry index keywords 27-4 Menu operations 27-5 Menu attribute resource names. 27-6 Attributes for menu entries 29-1 Attributes for frame and toplevel widgets 29-2 Label Attributes 29-3 Message Attributes 29-4 Bindings for scale widgets 29-5 ttributes for scale widgets 29-6 perations on the scale widget 30-1 Bindings for the scrollbar widget 30-2 Attributes for the scrollbar widget 30-3 Operations on the scrollbar widget 31-1 Entry bindings 31-2 Entry attribute resource names 31-3 Entry indices 31-4 Entry operations 32-1 Listbox indices 32-2 Listbox operations

32-3 The values for the selectMode of a listbox 32-4 Bindings for browse selection mode 32-5 Bindings for single selection mode 32-6 Bindings for extended selection mode 32-7 Bindings for multiple selection mode 32-8 Listbox scroll bindings 32-9 Listbox attribute resource names 33-1 Text indices 33-2 Index modifiers for text widgets 33-3 Attributes for text tags 33-4 Options to the search operation 33-5 Window and image alignment options 33-6 Options to the window create operation 33-7 Options to the image create operation 33-8 Bindings for the text widget 33-9 Operations for the text widget 33-10 Text attribute resource names 34-1 Arc attributes 34-2 Bitmap attributes 34-3 Image attributes 34-4 Line attributes 34-5 Oval attributes 34-6 Polygon attributes 34-7 Rectangle attributes 34-8 Indices for canvas text items 34-9 Canvas operations that apply to text items 34-10 Text attributes 34-11 Operations on a canvas widget

34-12 Canvas postscript options 34-13 Canvas attribute resource names 35-1 The selection command 35-2 The clipboard command 36-1 Options to tk_messageBox 36-2 Options to the standard file dialogs 36-3 Options to tk_chooseColor 36-4 The focus command 36-5 The grab command 36-6 The tkwait command 37-1 Size attribute resource names 37-2 Border and relief attribute resource names 37-3 Highlight attribute resource names 37-4 Layout attribute resource names 38-1 Color attribute resource names 38-2 Windows system colors 38-3 Macintosh system colors 38-4 Visual classes for displays 38-5 Summary of the image command 38-6 Bitmap image options 38-7 Photo image attributes 38-8 Photo image operations 38-9 Copy options for photo images 38-10 Read options for photo images 38-11 Write options for photo images 38-12 Cursor attribute resource names 39-1 Font attributes

39-2 X Font specification components 39-3 The font command 39-4 Layout attribute resource names 39-5 Selection attribute resource names 40-1 Options to the send command 41-1 Size, placement and decoration window manager operations 41-2 Window manager commands for icons 41-3 Session-related window manager operations 41-4 Miscellaneous window manager operations 41-5 send command information 41-6 Window hierarchy information 41-7 Window size information 41-8 Window location information 41-9 Virtual root window information 41-10 Atom and window ID information 41-11 Colormap and visual class information 45-1 The Tcl source directory structure 45-2 The installation directory structure 45-3 Standard configure flags 45-4 TEA standard Makefile targets 46-1 Configuration flags and corresponding C types 48-1 Changes in color attribute names 52-1 The testthread command 52-2 The dde command options

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

PrefaceTcl stands for Tool Command Language. Tcl 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 (as explained on page lii) and use them freely in your application, even if it is commercial. The Tcl interpreter has been ported from UNIX to DOS, Windows, OS/2, NT, and Macintosh environments. The Tk toolkit has 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 10 years since I was introduced to Tcl, and about five years since the first edition of this book. During the last several years I have been working under John Ousterhout, first at Sun Microsystems and now at Scriptics Corporation. I have managed to remain mostly a Tcl programmer while others in our group have delved into the C implementation of Tcl itself. I've been building applications like HTML editors, e-mail user interfaces, Web servers, and the customer database we run 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

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 command language for your new application, or struggle to provide some sort of userprogrammability 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 set of commands 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. Tcl and Tk 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 user-interface 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, 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 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 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++. Javascript is a language from Netscape that is designed to script interactions with Web pages. Javascript is important because Netscape is widely deployed. 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Tcl and Tk VersionsTcl 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 third edition has been updated to reflect new features added through Tcl/Tk 8.2: 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 event-driven 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. Crossplatform 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 multithreaded 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Who Should Read This BookThis 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 T0cl 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

How to Read This BookThis book is best used in a hands-on manner, trying the examples at the computer. The book 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 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Other Tcl BooksThis book was the second Tcl book after the original book by John Ousterhout, the creator of Tcl. Since then, the number of Tcl books has increased remarkably. The following are just some of the books currently available. 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. Graphical Applications with Tcl & Tk (M&T Press, 1996) by Eric Johnson is oriented toward Windows users. The second edition is up-to-date with 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. CGI Developers Resource, Web Programming with Tcl and Perl (Prentice Hall, 1997) by John Ivler presents Tcl-based solutions to programming Web sites. Effective Tcl/Tk Programming (Addison Wesley, 1997) by Michael McLennan and Mark Harrison illustrate Tcl and Tk with examples and application design guidelines. Interactive Web Applications with Tcl/Tk (AP Professional, 1998) by Michael Doyle and Hattie Schroeder describes Tcl programming in the context of the Web browser plugin. 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. Tcl/Tk for Real Programmers (Academic Press, 1999) by Clif Flynt is another example-oriented book.

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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

On-line ExamplesThe 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 created with the Linux mkhybrid program, so it 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/

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Ftp ArchivesThe primary site for the Tcl and Tk distributions is given below as a Universal Resource Location (URL): ftp://ftp.scriptics.com/pub/tcl You can use FTP and log in to the host (e.g., ftp.scriptics.com) under the anonymous user name. Give your e-mail address as the password. The directory is in the URL after the host name (e.g., /pub/tcl). There are many sites that mirror this distribution. The mirror sites provide an archive site for contributed Tcl commands, Tk widgets, and applications. There is also a set of Frequently Asked Questions files. These are some of the sites that maintain Tcl archives ftp://ftp.neosoft.com/pub/tcl ftp://ftp.syd.dit.csiro.au/pub/tk ftp://ftp.ibp.fr/pub/tcl ftp://src.doc.ic.ac.uk/packages/tcl/ ftp://ftp.luth.se/pub/unix/tcl/ ftp://sunsite.cnlab-switch.ch/mirror/tcl ftp://ftp.sterling.com/programming/languages/tcl ftp://ftp.sunet.se/pub/lang/tcl ftp://ftp.cs.columbia.edu/archives/tcl ftp://ftp.uni-paderborn.de/pub/unix/tcl ftp://sunsite.unc.edu/pub/languages/tcl ftp://ftp.funet.fi/pub/languages/tcl You can use a World Wide Web browser like Mosaic, Netscape, Internet Explorer, or Lynx to access

these sites. Enter the URL as specified above, and you are presented with a directory listing of that location. From there you can change directories and fetch files. If you do not have direct FTP access, you can use an e-mail server for FTP. Send e-mail to [email protected] with the message Help to get directions. If you are on BITNET, send e-mail to [email protected]. You can search for FTP sites that have Tcl by using the Archie service that indexes the contents of anonymous FTP servers. Information about using Archie can be obtained by sending mail to [email protected] that contains the message Help.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

World Wide WebStart with these World Wide Web pages about Tcl: http://www.scriptics.com/ http://www.sco.com/Technology/tcl/Tcl.html http://www.purl.org/NET/Tcl-FAQ/ 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 has information about the book, but you must use its search facility to find the exact location. Start at: http://www.prenhall.com/

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

NewsgroupsThe comp.lang.tcl newsgroup is very active. It provides a forum for questions and answers about Tcl. Announcements about Tcl extensions and applications are posted to the comp.lang.tcl.announce newsgroup.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Typographic ConventionsThe more important examples are set apart with a title and horizontal rules, while others appear inline. 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 => 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

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Hot TipsThe 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Book OrganizationThe chapters of the book are divided into seven parts. The first part describes basic Tcl 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 Tcl commands in more detail, including string handling, data types, 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 data-processing 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. Safe-Tcl is used to provide a secure environment to execute applets downloaded over the network. 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. 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

What's New in the Third EditionThe third edition is up-to-date with Tcl/Tk 8.2. The main new Tcl/Tk features are Internationalization, which is covered in Chapter 15, a new regular expression engine, which is described in Chapter 11, and thread-safety. There is a new chapter about compiling C extensions, and there is a more complete C extension example. The chapters on Eval and the Web browser plugin received a thorough update. I made a light sweep through the remainder of the book correcting errors and improving examples. Perhaps the best addition for the reader is an all-new index. My favorite addition to the book is Chapter 18 that describes TclHttpd, a Web server built in Tcl. TclHttpd provides a number of nice ways to integrate a Web server with a Tcl application, replacing the standard CGI interface with something that is much more flexible and efficient. I have been using this server for the last year to build www.scriptics.com. This freely available server has been used to build several other products, plus it provides an easy way for you to bring up your own Web server.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

First Edition ThanksI would like to thank my managers and colleagues at Xerox PARC for their patience with me as 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, Carl Hauser, John Maxwell, Ken Pier, Marvin Theimer, and Mohan 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 e-mail: 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, Hkan 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Second Edition ThanksI 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, Safe-Tcl, 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Third Edition ThanksJohn Ousterhout continues his wonderful role as Tcl benefactor, now as founder of Scriptics 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 Hirschl, 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 Jones told me about a great indexing tool. I'd like to thank all the readers that drop me the encouraging note or probing question via e-mail. 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. 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Preface

Contact the AuthorI am always open to comments about this book. My e-mail address is [email protected]. It helps me sort through my mail if you put the word "book" or the title of the book into the e-mail subject line. Visit my Web site at: http://www.beedub.com/ for current news about the book and my other interests.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Part I: Tcl BasicsPart 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Part I. Tcl Basics

Chapter 1. Tcl FundamentalsThis chapter describes the 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. Tcl is designed to be a glue that assembles software building blocks 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Tcl CommandsTcl 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Hello, World!Example 1-1 The "Hello, World!" example. puts stdout {Hello, World!} => Hello, World! 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

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

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Command SubstitutionThe second form of substitution is command substitution. A nested command is delimited by 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. 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 45. 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Math ExpressionsThe 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 a bit 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)}]

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Backslash SubstitutionThe 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 61 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. The table 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 group and do not terminate the command. Second, a backslash as the 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.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

Grouping with Braces and Double QuotesDouble 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 52.

Square Brackets Do Not GroupThe 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 only of a nested command, you do not need to group it with double-quotes because the Tcl parser treats the whole nested command as part of the group. puts stdout [string length $s] The following is a redundant use of double quotes: puts stdout "[expr $x + $y]"

Grouping before SubstitutionThe 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 BracesIt 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 ExamplesIf 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 When you use Tk, you often use widget names as command names: $text insert end "Hello, World!"

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

ProceduresTcl 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. 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 and default values for arguments. These are described in detail in Chapter 7.

Top

Practical Programming in Tcl & Tk, Third Edition By Brent B. Welch

Table of Contents

Chapter 1. Tcl Fundamentals

A Factorial ExampleTo 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 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