Tcl/Tk Features - Elsevier

10 downloads 194 Views 185KB Size Report
The Tcl scripting language and its companion Tk user interface toolkit have ... object-oriented–style programming to Tcl) and expect, an extension that simpli-.
C H A P T E R

1 Tcl/Tk Features

Your first question is likely to be “What features will Tcl/Tk offer me that other languages won’t?” This chapter gives you an overview of the Tcl/Tk features. It covers the basics of what Tcl/Tk can offer you and what its strengths are compared to several alternatives. Tcl is a multi-faceted language. You can use Tcl as a command scripting language, as a powerful multi-platform interpreted language, as a rapid prototyping platform, or as a library of interpreter calls within another project. Tcl’s simple syntax makes single-use scripts [to replace repetitive command typing or graphical user interface (GUI) clicking] quick and easy to write. Tcl’s modularization and encapsulation features help you develop large projects (100,000 + lines of code). Tcl’s extensibility makes it easy to use Tcl as the base language across a broad range of projects, from machine control to database applications to electronic design applications, network test devices, and more. Dr. John Ousterhout received the 1997 Software System Award from the Association for Computing Machinery (ACM) for inventing Tcl/Tk. This award recognizes the development of a software system that has a lasting influence. The ACM press release says it well: The Tcl scripting language and its companion Tk user interface toolkit have proved to be a powerful combination. Tcl is widely used as the glue that allows developers to create complex systems using preexisting systems as their components. As one of the first embeddable scripting languages, Tcl has revolutionized the creation of customizable and extensible applications. Tk provides a much simpler mechanism to construct graphical user interfaces than traditional programming languages. The overall Tcl/Tk system has had substantial impact through its wide use in the developer community and thousands of successful commercial applications.

1

2

Chapter 1



Tcl/Tk Features

A researcher at the Software Engineering Institute of Carnegie Mellon University reported in review SEI-2003-TN-001 that Tcl/Tk is practical for developing large systems. Tcl is both free software and a commercially supported package. The core Tcl language is supported by a worldwide group of volunteers, and support can be purchased from ActiveState, Noumena Corporation, Cygnus, Proc Place, and others. The current central site for Tcl/Tk information is www.tcl.tk. The source code repository and some binary snapshots are maintained at http://sourceforge.net/projects/tcl/. Tcl/Tk runtime packages are included with the Linux and FreeBSD packages and with commercial UNIX distributions such as Solaris and HPUX. The current binaries for selected systems (including MS Windows, Linux, and Solaris) are available from ActiveState (www.activestate.com). One of the strengths of Tcl is the number of special-purpose extensions that have been added to the language. The most popular Tcl extension is Tk, which stands for Tool Kit. This extension provides tools for graphics programming, including drawing canvases, buttons, menus, and so on. The Tk extension is considered part of the Tcl core and is included in the source code distributions at SourceForge and most binary distributions. The next most popular extensions to Tcl are [incr Tcl] (which adds support for object-oriented–style programming to Tcl) and expect, an extension that simplifies controlling other applications and devices and allows many complex tasks to be easily automated. The proposal to add the [incr Tcl] extension to the standard Tcl distribution was approved in 2001. Adding the [incr Tcl] extension to the standard distribution assures developers that the core interpreter and extension revisions are in sync and work together flawlessly. The expect, BLT (which includes a very useful graph and bar-chart widget), TclX (which adds new programming tools to the base Tcl language), and many other extensions, packages, and tools are available as source from their primary sites and as binaries on many systems. These packages and others are included on the companion CD-ROM either separately or as part of ActiveState’s ActiveTcl release included on the CD-ROM.

1.1 Tcl Overview Tcl (pronounced either as the three letters or as “tickle”) stands for Tool Command Language. This name reflects Tcl’s strength as a scripting language for gluing other applications together into a new application. Tcl was developed by Dr. John Ousterhout while he was at the University of California at Berkeley. He and his group developed simulation packages that

1.1 Tcl Overview

needed macro languages to control them. After creating a few on-the-fly languages that were tailored to one application and would not work for another, they decided to create an interpreter library they could merge into the other projects. This provided a common parsing package that could be used with each project and a common base language across the applications. The original design goal for Tcl was to create a language that could be embedded in other programs and easily extended with new functionality. Tcl was also designed to execute other programs in the manner of a shell scripting language. By placing a small wrapper around the Tcl library, Dr. Ousterhout and his group created tclsh, a program that could be used as an interactive shell and as a script interpreter. Dr. Ousterhout expected that this solid base for building specialized languages around a common set of core commands and syntax would be useful for building specialized tools. However, as programmers created Tcl extensions with support for graphics, database interaction, distributed processing, and so on, they also started writing applications in pure Tcl. In fact, the Tcl language turned out to be powerful enough that many programs can be written using tclsh as an interpreter with no extensions. Today, Tcl is widely used for in-house packages, as an embedded scripting language in commercial products, as a rapid prototyping language, as a framework for regression testing, and for 24/7 mission-critical applications. The robustness of the Tcl interpreter is demonstrated by such mission-critical applications as controlling offshore oil platforms, product Q/A and Q/C operations, and running the NBC broadcasting studios. Many companies are open about use of Tcl, and many more consider Tcl their secret competitive edge.

1.1.1 The Standard Tcl Distribution Tcl is usually distributed with two interpreters (tclsh, commonly pronounced “ticklish,” and wish), support libraries, and on-line help. Tclsh is a text-based interpreter, and wish is the same basic interpreter with Tk graphics commands added. You can use the Tcl interpreter (tclsh) scripts as you would use UNIX shell scripts or MS-DOS batch (.bat) scripts to control and link other programs or use wish to create GUI interfaces to these scripts. The tclsh interpreter provides a more powerful environment than the standard UNIX shell or .bat file interpreters. The ActiveState ActiveTcl releases are sometimes called a Batteries Included version of Tcl, since the distribution includes the tclsh and wish interpreters and many more extensions, packages, and tools that have been compiled and tested together. The Tcl on-line help facility integrates into the native look and feel of the platform Tcl is installed on. On a UNIX/Linux platform, the man pages are installed under installation Directory/man/mann and can be accessed using the standard man command.

3

4

Chapter 1



Tcl/Tk Features

You may need to add the path to the installed manual pages to your MANPATH environment variable. On Microsoft Windows platforms, you can access the Tcl help from the Start menu, shown in the following illustration.

This will open a window for selecting which help you need. The window is shown in the following illustration.

Selecting Tcl Built-In Commands from that menu will open a window like that shown in the following illustration. You can select from this window the page of help you need.

1.1 Tcl Overview

On a Macintosh, the help files are kept in the Tcl/Tk HTML Manual folder inside the Tcl/Tk folder, as shown in the following illustration.

5

6

Chapter 1



Tcl/Tk Features

Opening that folder will display a list of the available help files, and selecting one of the help files will open a browser window for displaying the HTML document (see following illustration).

1.2 Tcl As a Glue Language A command glue language is used to merge several programs into a single application. UNIX programmers are familiar with the concept of using the output from one program as the input of another via pipes. With a glue language, more complex links between programs become possible. For example, several programs that report network behavior can be merged with a glue language to create a network activity monitor. Instead of the linear data flow of a set of piped programs, you can have a tree-like data flow in which several sets of data flow into one application. There are good reasons to use simple glue language scripts in your day-to-day computing work: ■

A script can glue existing programs into a new entity. It is frequently faster to glue together several small programs to perform a specific task than it is to write a program from scratch.



A script can repeat a set of actions faster and more reliably than you can type. This is not to disparage your typing skills, but if you have to process 50 files in some consistent manner it will be faster to type a five-line script and have that loop through the file names than to type the same line 50 times.



You can automate actions that would otherwise take several sets of window and mouse operations. If you have spent much time with GUI programs using Microsoft Windows, Mac OS, or the X Window System, you have probably noticed that there are certain operations you end up doing over and over again, without a hot button you can use to invoke a particular set of button and mouse events. With a scripting language, you can automate a set of actions you perform frequently.



The script provides a record of commands and can act as procedure documentation.

1.2 Tcl As a Glue Language

For example, I create a new release of the TclTutor package (a copy of which is included on the companion CD-ROM) several times a year. This process involves several steps: 1. Copy the correct files to a release directory. 2. Create a zip file. 3. Convert the zip file to a self-extracting executable. At each step, there are several mouse selections and button clicks. None of these are particularly difficult or time consuming, but each is a potential error in building the package. I go through this procedure several times while I test that the new distribution works correctly and the new code behaves properly. I have automated this procedure with a small Tcl script. Since the script will be consistent, I don’t have to worry about missing a file because I released a button too early, and the script ensures a consistent release format. The script is better than I am at remembering all the steps in the release process. If you have written scripts using the Bourne shell under UNIX, or .bat files under MS-DOS/MS Windows, you know how painful it can be to make several programs work together. The constructs that make a good interactive user shell don’t necessarily make a good scripting language. Using Tcl, you can invoke other programs, just as you would with shell or .bat scripts, and read any output from those programs into the script for further processing. Tcl provides the string processing and math functionality of awk, sed, and expr without needing to execute other programs. It is easier to write Tcl scripts than Bourne shell scripts with awk and sed, since you have to remember only a single language syntax. Tcl scripts also run more efficiently, since the processing is done within a single executable instead of constantly executing new copies of awk, sed, and so on. Note that you can only use a script to control programs that support a non-GUI interface. Many GUI-based programs have a command line interface suitable for scripting. Others may support script languages of their own or have a dialogbased mode. Under MS Windows, you can also interact applications using Tcl’s DDE extension. You can use a wish script as a wrapper around a set of programs originally designed for a text-based user interaction (query/response, or one-at-a-time menu choices) and convert the programs into a modern GUI-based package. This is a very nice way of adding a midlife kicker to an older package by hiding the old-style interactions from users more accustomed to graphical environments. For example, we used a text-based problem-tracking system at one company. The user interface was a series of questions, such as “What product is the problem being reported against?” and “What revision is this product?” It took under an hour to write a wish front end that had buttons to select the products, text entry fields for the revisions and problem descriptions, and so on. This GUI invoked the

7

8

Chapter 1



Tcl/Tk Features

old user interface when the Submit button was pressed and relayed the selected values to that program as the prompts were received. The GUI interface reduced the time and error count associated with filling out a report by reducing the amount of typing and providing a set of choices for models and revisions. This technique for updating the user interface is faster than rewriting the application and is less prone to introducing new errors, since all original (debugged) code is left untouched.

1.2.1 Tcl Scripts Compared to UNIX Shell Scripts The following are advantages Tcl provides over UNIX shell scripts. ■

Easier handling of program output. Parsing program output in a shell script is possible but not always easy. With Tcl, it is simple. Instead of saving the original command line variables, changing the field separator, reading a line of output, and using the shell set command to parse the line into new command arguments, or invoking sed or awk to process some text, you can read a line from a program’s output just as if it had been entered at a keyboard. Then you can use Tcl’s powerful string and list operators to process the input, assign values to variables, perform calculations, and so on.



More consistent error handling in Tcl. It can be difficult to distinguish between an error return and valid output in shell programming. Tcl provides a mechanism that separates the success/failure return of a program from the textual output.



Consistent language. When you write UNIX shell scripts, you end up using copies of awk and sed to perform processing the shell cannot do. You spend part of your time remembering the arcane awk and sed command syntax, as well as the shell syntax. Using Tcl, you can use a single language to perform all of the tasks, such as program invocation, string manipulation, and computations. You can expend your effort solving the original problem instead of solving language issues.



Speed. A single self-contained script running within the Tcl interpreter is faster and uses fewer machine resources than a UNIX shell script that frequently needs to spawn other programs. This is not to say that a program written in Tcl is faster than one written in the C language. A string-searching program written in Tcl is probably slower than a string-searching program written in C. But a script that needs to find strings may run faster with a string-searching subroutine in Tcl than one written for the UNIX shell that constantly forks copies of another executable. When it is appropriate to invoke a special-purpose program, it is easily done with the Tcl exec command.



GUI support. You can use Tk to add a graphical interface to your scripts. Under UNIX, wish supports the Motif look and feel. Under Windows and Mac, Tk supports the native Windows or Macintosh look and feel.

1.3 Tcl As a General-Purpose Interpreter

According to reports in comp.lang.tcl, a GUI written with wish sometimes runs faster than the same GUI written in C with the Motif library. For lightweight GUIs, a Tk GUI is frequently faster than a Java GUI.

1.2.2 Tcl Scripts Compared to MS-DOS .bat Files Tcl has so much more power than .bat files that there is actually very little comparison. The power of Tcl/Tk more closely resembles that of Visual Basic. Tcl/Tk is compared to Visual Basic in the next section, in the context of comparison of general-purpose interpreters. The following are advantages a Tcl script provides over an MS-DOS .bat file. ■

Access to the output of programs invoked from script. The .bat file interpreter simply allows you to run programs, not to access a program’s output. With Tcl you can start a program, read its output into your script, process that data, send data back to that task, or invoke another task with the modified data.



Control structures. Tcl has more control structures than .bat files, including while loops, for loops, if/else, and switch.



String manipulation. The .bat files do not support any string manipulation commands. Tcl provides a very rich set of string-searching and manipulation commands.



Math operations. Tcl provides a full set of arithmetic functions, including arithmetic, trig, and exponential functions and multiple levels of parentheses.



Program control. An MS-DOS .bat file has very limited control of other programs invoked by the .bat file. Tcl provides a great deal of control. In particular, when a GUI program is invoked from a .bat file under Windows 95 or Windows NT, the control may return to the .bat file before the program has ended. This is a problem if you were intending to make use of the results of the first program you invoked in the next program. Tcl can prevent the second program from starting until after the first program has completed its processing, or allow multiple programs to be run simultaneously.



GUI support. You can use Tk to make your scripts into GUIs. Wish supports a look and feel that matches the standard MS Windows look and feel, and thus scripts you write with wish will look just like programs written in Visual C++, Visual Basic, or other Microsoft development environments.

1.3 Tcl As a General-Purpose Interpreter The Tcl/Tk interpreter provides the following advantages over other interpreters. ■

Multi-platform. The same script can be run under Microsoft Windows 3.1, Microsoft Windows 95/98, Microsoft Windows NT/2000/XP, Apple Mac OS

9

10

Chapter 1



Tcl/Tk Features

and OS/X, and UNIX or Linux. Tcl has also been ported to Digital Equipment’s VMS and real-time kernels, such as Wind River Systems’ VxWorks, and even to platforms such as Palm OS and Win CE. ■

Speed. Since version 8.0 (released in 1998), the Tcl interpreter performs a runtime compilation of a script into a byte code. Running the compiled code allows a Tcl script to run faster than Visual Basic or Perl.



Power. Tcl supports most of the modern programming constructs. ■

■ ■





Modularization in the form of subroutines, libraries (including version control), and namespaces. Standard program flow constructs: if, while, for, foreach, and switch. Rich set of variable types: integers, floating point, strings, lists, and associative arrays. Exception handling. The Tcl catch and error commands provide an easy method of handling error conditions. Support for traditional program flow and event-driven programming.



Rich I/O implementation. Tcl can perform I/O operations with files, devices, keyboard/screen, other programs, or sockets.



Powerful string manipulation commands. Tcl includes commands for searching and replacing strings or single characters, extracting and replacing portions of strings, and converting strings into lists, as well as commands that implement regular expressions for searching and replacing text.



Extensibility. Tcl extensions add a few new commands to the Tcl/Tk language to extend the interpreter into a new application domain. This allows you to build on previous development and greatly reduces startup time when working on a new problem, in that you only need to learn a couple of new commands, instead of an entire new language.

1.3.1 Tcl/Tk Compared to Visual Basic Of the currently available languages, Visual Basic is probably the closest in functionality to Tcl/Tk. The following are reasons Tcl/Tk is a better choice. ■

Tcl/Tk scripts run on multiple platforms. Although the primary market for software may be the MS Windows market, you might also want to have Apple and UNIX markets available to your sales staff.



Tcl/Tk scripts have support for Internet-style distributed processing, including a secure, safe interpreter that allows an application to run untrusted applications securely.



Tk provides more and finer control of widgets. Wish allows you to bind actions to graphics objects as small as a single character in a text window or as large as an application window.

1.3 Tcl As a General-Purpose Interpreter ■

Tcl has better support for library modules and version levels. A Tcl script can check for a particular version of its support libraries and not run if they are not available.

You might prefer Visual Basic over Tcl if you are writing a package that will only need to interact with the Microsoft applications. Many Microsoft applications use Visual Basic as their scripting language, and there are off-the-shelf components written in Visual Basic you can merge into these applications. Native Tcl supports only the DDE interprocess communication protocol for interacting with other MS Windows applications. Support for OLE and COM objects can be added to Tcl with the TOCX extension, available at www.cs.cornell.edu/Info/Projects/zeno/tocx/, or the TclBridge package from Mistachkin Systems (www.tclbridge.com/index.html). A demo version of TclBridge is included on the companion CD-ROM under Tools. Support for SOAP can be added with the Tcl SOAP extension, available at http://tclsoap.sourceforge.net/.

1.3.2 Tcl/Tk Compared to Perl Tcl/Tk often competes with Perl as an application scripting language. The following are advantages Tcl/Tk offers over Perl. ■

Simpler syntax. Tcl code can be more easily maintained than Perl code. The rich set of constructs available to Perl programmers allows some very write-only programming styles. A Perl programmer can write code that strongly resembles UNIX shell language, C code, or awk scripts. Tcl supports fewer syntactic methods of accomplishing the same action, making Tcl code more readable.



Speed. The Tcl 8.0 interpreter byte-compiled code runs as fast or faster than Perl 5 interpreter code.



Better GUI support. Native Perl has no GUI support. A couple of Tk/Perl mergers are available, but Tk is better integrated with Tcl.



Internationalization. Tcl has had fully integrated Unicode support since the 8.1 release (in 1999).



Thread safety. While Tcl does not support multiple threads, the Tcl interpreter is thread safe and can be used with multi-threaded applications.

1.3.3 Tcl/Tk Compared to Python The base Python interpreter is probably the closest to Tcl in functionality and use. Both are interpreted scripting languages designed to either glue other applications into a new super-application or to construct new applications from scratch, and both support easy extension with new C library packages. The Python and Tcl developers actively adopt each other’s ideas, leading to a condition in which the best features of each language are in both languages (and if that

11

12

Chapter 1



Tcl/Tk Features

is not true at this moment, it will be true again soon). Many programmers know both languages, and the use of one over the other is as much personal preference as anything. The following are the advantages of Tcl. ■

Simpler syntax. The Tcl language is a bit simpler and easier to learn than Python.



Integrated with Tk. Both Python and Perl have adopted the Tk graphics library as their graphics package. The integration of Tk with Tcl is cleaner than the integration with either Perl or Python. (After all, Tk was designed to work with Tcl.)



Less object oriented. The base Tcl interpreter supports simple object-oriented programming with the namespace command or a C++/Java style of objectoriented programming with the [incr Tcl] extension, but does not require that you use either.

Python is built around a concept of objects that does not quite match the C++/Java class model, and there is no Python extension to get a complete object-oriented behavior with public, protected, and private data.

1.3.4 Tcl/Tk Compared to Java The primary language for multi-platform applications today is Java. Tcl and Java have some similarities but are really designed to solve two different problem sets. Java is a system programming language, similar to C and C++, whereas Tcl is an interpreted scripting language. In fact, you can write Tcl extensions in Java, and Tcl can load and execute Java code. The following are advantages Tcl offers over Java. ■

Better multi-platform support. Tcl runs on more platforms than Java. Java requires thread support, which is unavailable on many older UNIX platforms. Tcl has also been ported to real-time kernels such as VxWorks and Q-nix.



Faster for prototyping. The strength of an object-oriented language is that it makes you think about the problem up front and to perform a careful design before you code. Unfortunately, for many projects, you do not know the requirements up front and cannot design a class structure until you understand the solutions better. Tcl/Tk is great for whipping out a quick prototype, seeing what truly answers the user’s needs and what was not necessary, and then creating a serious design from a solid set of requirements.



Better GUI support. The Tk widgets are easier to work with and provide higherlevel support than the Java graphics library.



Configurable security levels. Tcl supports a different security model than the Java Applet model, making Tcl an ideal language for Internet program development. With Tcl, objects with various origins can be given varying levels of access to your system. By default, the Tcl browser plug-in modules come with three security levels: untrusted (no access to file system or sockets), slightly trusted (can read files or sockets, but not both), and fully trusted (can access all I/O types.) With Tcl, you can configure your own security model, allowing access to a subset of the file system or specific devices, for instance.

1.6 Tcl As a Rapid Development Tool ■

Smaller downloadable objects. Because the Tcl libraries live on the machine where an application runs, there is less to download with a Tcl/Tk application than a similar set of functionality written in Java.

1.4 Tcl As an Extensible Interpreter Many programming groups these days have a set of legacy code, a set of missions, and a need to perform some sort of rapid development. Tcl can be used to glue these code pieces into new applications. Using Tcl, you can take the existing project libraries and turn them into commands within a Tcl interpreter. Once this is done, you have a language you can use to develop rapid prototypes or even shippable programs. Merging the existing libraries into the interpreter gives you a chance to hide sets of calling conventions that may have grown over several years (and projects) and thus expose the application developer to a consistent application programmer interface (API). This technique gives you a chance to graft a graphics interface over older, non-GUI–based sets of code.

1.5 Tcl As an Embeddable Interpreter Programs frequently start as a simple proof of concept with hard-coded values. These values quickly evolve into variables that can be set with command line arguments. Shortly after that, the command lines get unwieldy, and someone adds a configuration file and a small interpreter to parse the configuration. The macro language then grows to control program flow as well as variables. Then it starts to get messy. At the point where you need a configuration file, you can merge in a Tcl interpreter instead of writing new code to parse the configuration file. You can use Tcl calls to interpret the configuration file, and as the requirements expand you will already have a complete interpreter available, instead of hacking in features as people request them.

1.6 Tcl As a Rapid Development Tool Tcl has a simple and consistent syntax at its core, which makes it an easy language to learn. At the edges, Tcl has many powerful extensions that provide less commonly needed functionality. These extensions include the following: ■

General-purpose programming extensions such as TclX (new commands to make Tcl more useful for sys-admins) and [incr Tcl] (a full-featured objectoriented extension)

13

14

Chapter 1



Tcl/Tk Features ■

Application-specific extensions such as OraTcl and SybTcl (for controlling Oracle or Sybase database engines)



Special-purpose hardware extensions such as the extension for controlling a National Scientific card described in the Real-World Tcl/Tk bonus book on the companion CD-ROM



Special-purpose software libraries such as the TSIPP extension, which lets you generate 3D images using the SIPP library from Tcl

You can think of Tcl as a simple language with a rich set of libraries. You can learn enough of the core Tcl commands to start writing programs in under an hour and then extend your knowledge as the need arises. When a task requires some new tools (SQL database interface, for instance), you have to learn only those new commands, not an entire new language. This common core with extensions makes your life as a programmer easier. You can take all the knowledge you gained doing one project and apply most of it to your next project. This simplicity at the core with complexity in the extensions makes Tcl/Tk very suitable for rapid prototype development projects. During the 1995 Tcl/Tk Workshop, Brion Sarachan described the product that General Electric developed for NBC to control television network distribution (the paper describing this work is printed in the Conference Proceedings of the Tcl/Tk Workshop, July 1995). The first meeting was held before the contract was awarded and included the engineers, management, and sales staff. After discussing the basic requirements, the sales and management groups continued to discuss schedules, pricing, and such, while the engineers went into another room and put together a prototype for what the system might look like. By the time the sales and management staff were done, the engineers had a prototype to show. This turnaround speed had a lot to do with GE being awarded that contract. The GE group expanded their prototype systems with various levels of functionality for the people at NBC to evaluate. As the project matured, the specifications were changed on the basis of the experience with prototypes. The ease with which Tcl/Tk code can be extended and modified makes it an ideal platform for this type of project. The ability to extend the interpreter is a feature that separates Tcl from the other multi-platform and rapid development languages. Tcl interpreters can be extended in several ways, ranging from adding more Tcl subroutines (called procs in Tcl) to merging C, Java, or even assembly code into the interpreter. Studies have found that 80% of a program’s runtime is spent in 20% of the code. The extensible nature of Tcl allows you to win at that game by rewriting the compute-intensive portion in a faster language while leaving the bulk of the code in the more easily maintained and modified script language. This form of extensibility makes Tcl/Tk useful as the basis for a suite of programs. In a rapid prototype phase, a Tcl/Tk project can evolve from a simple set of backof-the-envelope designs to a quick prototype done entirely in Tcl. As the project

1.8 Shipping Products

matures, the various subroutines can be modified quickly and easily, as they are all written in Tcl. Once the design and the main program flow have stabilized, various Tcl/Tk subroutines can be rewritten in C or Java to obtain the required performance. Once one project has evolved to this state, you have an interpreter with a set of specialized commands that can be used to develop other projects in this problem domain. This gives you a platform for better rapid prototyping and for code reuse.

1.7 GUI-Based Programming The Tcl distribution includes the Tk graphics extensions of Tcl. The Tk extension package provides an extremely rich set of GUI tools, ranging from primitive widgets (such as buttons, menus, drawing surfaces, text windows, and scrollbars) to complex compound widgets (such as file selectors). Any visual object can have a script bound to it so that when a given event happens a particular set of commands is executed. For example, you can instruct a graphics object to change color when the cursor passes over it. You can bind actions to objects as trivial as a single punctuation mark in a text document or as large as an entire display. Chapters 8 through 12 describe using Tk to build simple GUIs, active documents (such as maps and blueprints) that will respond to user actions, and complex, custom graphics objects.

1.8 Shipping Products When it comes time to ship a product, you can either ship the Tcl scripts and Tcl interpreter or merge your Tcl script into an interpreter to create a Tcl-based executable. The advantage of shipping the Tcl scripts is that competent users (or clever programs) can modify and customize the scripts easily. The disadvantages include the need for the user to have the proper revision level of Tcl available for the script to run and the possibility that someone will reverse-engineer your program. A Tcl script can be wrapped into a copy of the interpreter, to create a binary executable that will run only this script. (See the discussions of starkit, the TclPro wrapper, and Dennis Labelle’s Freewrap in Chapter 13.) With this technique, you can develop your program in a rapid development environment and ship a single program that does not require installation of the Tcl interpreter and has no human-readable code.

15

16

Chapter 1



Tcl/Tk Features

1.9 Bottom Line Tcl/Tk is ■

A shell scripting language



A multi-platform language



An extensible interpreter



An embeddable interpreter



A graphics programming language

Tcl/Tk is useful for ■

Rapid prototyping



Shippable product



Use-once-and-dispose scripts



Mission-critical, 24/7 applications



GUI-based projects



Multi-platform products



Adding GUIs to existing text-oriented programs



Adding new functionality to old code libraries

1.10 Problems The following numbering convention is used in all Problem sections. Number Range Description of Problems 100–199

These problems review the material covered in this chapter. They can be answered in a few words or a short (1–5-line) script. Each problem should take under a minute to answer.

200–299

These problems go beyond the details presented in this chapter. They may require some analysis of the material or command details not covered in the chapter. They may require reading a man page or making a web search. They can be answered with a few sentences or a 5–50-line script. Each problem should take under 10 minutes to answer.

300–399

These problems extend the material presented in this chapter. They may require referencing other sources. They can be answered in a few paragraphs or a few hundred lines of code. Each exercise may take a few hours to complete.

1.10 Problems

100. Can a Tcl script invoke other programs? 101. Can Tcl scripts perform math operations? 102. Is Tcl useful for rapid development? 103. Who developed the Tcl language? Where? Why? 104. Which of these statements is correct? Tcl is a. A single language b. A language core with many extensions c. A graphics language 105. How would you deploy a Tcl/Tk program if you could not be certain the client would have the right Tcl/Tk version installed on their system? 106. Can a Tcl interpreter be extended with another library? 107. Can the Tcl interpreter be embedded into another application?

200. Why would you use Tcl instead of C? 201. Why would you use C or C++ instead of Tcl? 202. Why would you use Tcl instead of a .bat file? 203. What type of requirement would preclude Tcl as the sole development language?

300. Some computer languages were developed to solve problems in a particular domain (SQL for database manipulation, COBOL for business applications, FORTRAN for calculations). Others were developed to support particular programming styles (functional languages such as Scheme and Lisp, object-oriented languages such as C++ and Java). Other groups of languages were created by developers who wanted a new, better tool (C for system development, Perl for systems scripts). Describe the strengths and weaknesses of each of these design philosophies. 301. Tcl can be used to glue small applications into a single larger application, to merge the functionality of multiple libraries into a single application, or to write completely self-contained applications. Why would you use one technique over another?

17