Tcl/Tk Programming for the Absolute Beginner KURT WALL © 2008 Thomson Course Technology, a division of Thomson Learning Publisher and General Inc. All rights reserved. No part of this book may be reproduced or trans- Manager, Thomson Course mitted in any form or by any means, electronic or mechanical, including Technology PTR: photocopying, recording, or by any information storage or retrieval sys- Stacy L. Hiquet tem without written permission from Thomson Course Technology PTR, Associate Director of except for the inclusion of brief quotations in a review. Marketing: The Thomson Course Technology PTR logo and related trade dress are Sarah O’Donnell trademarks of Thomson Course Technology, a division of Thomson Manager of Editorial Learning Inc., and may not be used without written permission. Services: All trademarks are the property of their respective owners. Heather Talbot Important: Thomson Course Technology PTR cannot provide software Marketing Manager: support. Please contact the appropriate software manufacturer’s tech- Mark Hughes nical support line or Web site for assistance. Acquisitions Editor: Thomson Course Technology PTR and the author have attempted Mitzi Koontz throughout this book to distinguish proprietary trademarks from de- Project Editor and scriptive terms by following the capitalization style used by the manu- Copy Editor: facturer. Marta Justak Information contained in this book has been obtained by Thomson Technical Reviewer: Course Technology PTR from sources believed to be reliable. However, Rick Reynolds because of the possibility of human or mechanical error by our sources, Thomson Course Technology PTR, or others, the Publisher does not PTR Editorial Services guarantee the accuracy, adequacy, or completeness of any information Coordinator: and is not responsible for any errors or omissions or the results obtained Erin Johnson from use of such information. Readers should be particularly aware of the fact that the Internet is an ever-changing entity. Some facts may have Interior Layout Tech: changed since this book went to press. Value Chain Educational facilities, companies, and organizations interested in mul- Cover Designer: tiple copies or licensing of this book should contact the Publisher for Mike Tanamachi quantity discount information. Training manuals, CD-ROMs, and por- Indexer: tions of this book are also available individually or can be tailored for Sharon Shock specific needs. Proofreader: ISBN-10: 1–59863–438–0 Melba Hopper ISBN-13: 978–1-59863- 438–9 eISBN-10: 1-59863-636-7 Library of Congress Catalog Card Number: 2007903971 Printed in the United States of America 08 09 10 11 12 TW 10 9 8 7 6 5 4 3 2 1 Thomson Course Technology PTR, a division of Thomson Learning Inc. 25 Thomson Place Boston, MA 02210 http://www.courseptr.com To my wife, Kelly, who truly is flesh of my flesh and bone of my bone. A CKNOWLEDGMENTS T he image of writing as a solitary person laboring in the dark of night to produce a literary masterpiece is a grand fiction, usually perpetuated by writers who know better. I might have worked in the dark of night, but that’s the only part of the image that holds up to serious scrutiny. Writing a book is a team effort. My agent, Marta Justak, helped me get the book and took some lumps intended for me when I fell behind on the schedule. As usual, Marta, you’re the best. Let’s do this again, but leave out the parts that weren’t fun. The editorial team was first rate. Special thanks to Mitzi Koontz for graciously accommodating my request to extend the schedule; Marta Justak, the copy editor, eliminated a distressing number of typos and grammatical mistakes; Melba Hopper, proofreader extraordinaire, gets extra credit for understanding the con- ventions I adopted and perversely managed not to follow; and Rick Reynolds, my technical editor, noted some algorithmic subtleties and downright blunders that would have embarrassed me and misled you. Sharon Shock, the indexer, had the thankless but vital task of creating the index. A good index makes the difference between a book that sits on the shelf and a book that gets dog-eared and marked- up. Thanks to you all—it’s a much better book as a result of your ministrations. I appreciate the help and support of my colleagues at Panasas, the inhabitants of the #tcl channel on Freenode, and my friends. Panasas tolerated my bleary-eyed appearances at the office. The Tcl and Tk pros on #tcl answered oddball questions about Tcl and Tk features. My friends provided support and encouragement and said: “Ooh! Aaah!” at just the right times. I would be remiss if I failed to thank my wife. Kelly gave me the space and time to work on the book that I would otherwise have spent with her. She also told me not to stay up too late working on the book, advice I would have done well to heed. Poots the cat provided needed comic relief and company at 2:00 a.m. All the support and assistance notwithstanding, I take full responsibility for any errors and mistakes that remain. A A BOUT THE UTHOR W hen he isn’t writing a book (including numerous Linux books), KKurt Wall might be found cooking, drinking coffee, working at his day job, playing in his garden, trying not to hurt himself while learning to build furniture, or sitting in front of his computers. Kurt dislikes writing about himself in the third person. This page intentionally left blank Table of Contents Chapter 1 Introducing Tcl and Tk............................................. 1 What Is Tcl?.............................................................................................................................. 1 What Is Tk?............................................................................................................................... 2 What Makes Tcl and Tk Different?.................................................................................... 3 Why Use Tcl and Tk?.............................................................................................................. 5 Getting Tcl and Tk.................................................................................................................. 6 Installing Tcl and Tk on Linux................................................................................... 6 Installing Tcl and Tk on Windows............................................................................ 7 Installing Tcl and Tk on OS X................................................................................... 13 Installing Tcl and Tk from Source.......................................................................... 18 Chapter 2 Running Tcl Programs........................................... 23 Invoking the Interpreter.................................................................................................... 23 Executing Tcl Commands Interactively......................................................................... 25 Creating Tcl Command Files............................................................................................. 27 Chapter 3 Doing Mathematics.................................................. 33 Guessing Numbers............................................................................................................... 33 Language Fundamentals.................................................................................................... 34 Comments..................................................................................................................... 35 Commands.................................................................................................................... 36 Command Substitution............................................................................................. 38 Grouping........................................................................................................................ 41 Grouping with Double Quotes................................................................................. 42 Grouping with Braces................................................................................................. 42 Variables........................................................................................................................ 43 Procedures..................................................................................................................... 46 Getting User Input............................................................................................................... 48 Basic Mathematical Operators......................................................................................... 50 Conditional Execution: The if Command.................................................................... 52 Analyzing the Guessing Numbers Program.................................................................. 56 Looking at the Code.................................................................................................... 56 viii Tcl/Tk Programming for the Absolute Beginner Understanding the Code........................................................................................... 57 Modifying the Code..................................................................................................... 57 Chapter 4 Strings, Strings, Everywhere Strings!................ 59 Mad Libs.................................................................................................................................. 59 The string Command........................................................................................................ 60 Comparing Strings.............................................................................................................. 62 The compare Option.................................................................................................... 63 The equal Option........................................................................................................ 65 The match Option........................................................................................................ 66 Inspecting Strings................................................................................................................ 68 The length and bytelength Options..................................................................... 68 The index Option........................................................................................................ 68 The first and last Options.................................................................................... 69 The range Option........................................................................................................ 70 The replace Option.................................................................................................... 71 The is Option............................................................................................................... 73 Modifying Strings................................................................................................................ 76 Repeating Strings........................................................................................................ 76 Switching Case............................................................................................................. 76 Trimming Strings........................................................................................................ 77 Appending Strings...................................................................................................... 78 Looping Commands............................................................................................................ 78 Looping with the while Command........................................................................ 79 Iterative Loops: The for Command........................................................................ 81 Analyzing Mad Libs............................................................................................................. 83 Looking at the Code.................................................................................................... 83 Understanding the Code........................................................................................... 84 Modifying the Code..................................................................................................... 85 Chapter 5 Working with Lists.................................................. 87 Playing Blackjack................................................................................................................. 87 What Is a Tcl List?................................................................................................................ 88 Creating Lists........................................................................................................................ 89 Appending Lists.................................................................................................................... 90 Merging Lists......................................................................................................................... 90 Accessing List Elements..................................................................................................... 91 Accessing Specific List Elements............................................................................. 92 Modifying Lists..................................................................................................................... 94 Inserting New Elements............................................................................................ 94 Replacing Elements.................................................................................................... 95 Searching and Sorting Lists............................................................................................... 96 Contents ix Searching 101............................................................................................................... 96 Sorting............................................................................................................................ 99 Additional List Operations.............................................................................................. 102 Strings to Lists............................................................................................................ 102 Lists to Strings............................................................................................................ 103 Looping with the foreach Command.......................................................................... 104 Conditional Execution: The switch Command......................................................... 105 Interrupting Loop Execution.......................................................................................... 108 Analyzing Playing Blackjack........................................................................................... 110 Looking at the Code.................................................................................................. 110 Understanding the Code......................................................................................... 112 Modifying the Code................................................................................................... 113 Chapter 6 Creating and Using Arrays................................... 115 What’s the Word?.............................................................................................................. 115 The Differences Between Arrays and Lists.................................................................. 116 Working with Arrays........................................................................................................ 117 Getting Information about Arrays........................................................................ 118 Converting Lists to Arrays....................................................................................... 120 Converting Arrays to Lists....................................................................................... 121 Retrieving Array Elements...................................................................................... 122 Searching Arrays........................................................................................................ 123 Grace Under Pressure....................................................................................................... 124 Dealing with Exceptions: The catch Command............................................... 124 Raising Errors: The error Command................................................................... 126 Examining Variables......................................................................................................... 128 Analyzing What’s the Word?.......................................................................................... 129 Looking at the Code.................................................................................................. 129 Understanding the Code......................................................................................... 130 Modifying the Code................................................................................................... 131 Chapter 7 Writing Tcl Procedures........................................ 133 Fortune Teller..................................................................................................................... 133 What Is a Procedure?........................................................................................................ 134 Defining Procedures......................................................................................................... 135 Defining Procedures with Default Values.......................................................... 136 Defining Procedures with Variable Arguments................................................ 137 Understanding Variable and Procedure Scope.......................................................... 139 Analyzing Fortune Teller................................................................................................. 142 Looking at the Code.................................................................................................. 142 Understanding the Code......................................................................................... 143 Modifying the Code................................................................................................... 144
Description: