Practical Programming in Tcl and Tk

Total Page:16

File Type:pdf, Size:1020Kb

Practical Programming in Tcl and Tk Practical Programming in Tcl and Tk Brent Welch DRAFT, January 13, 1995 Updated for Tcl 7.4 and Tk 4.0 THIS IS NOT THE PUBLISHED TEXT THE INDEX IS INCOMPLETE SOME SECTIONS ARE MISSING THE MANUSCIRPT HAS NOT BEEN EDITED GET THE REAL BOOK: ISBN 0-13-182007-9 An enhanced version of this text has been published by Prentice Hall: ISBN 0-13-182007-9 Send comments via email to [email protected] with the word “book” in the subject. http://www.sunlabs.com/~bwelch/book/index.html The book is under copyright. Print for personal use only. This on-line DRAFT is available curtesty the kind folks at PH. Table of Contents 1. Tcl Fundamentals ............................................. 1 Getting Started ............................................................1 Tcl Commands .............................................................2 Hello World ..................................................................3 Variables ......................................................................3 Command Substitution ................................................4 Math Expressions ........................................................4 Backslash Substitution ................................................6 Double Quotes .............................................................7 Procedures ...................................................................7 A While Loop Example ..................................................8 Grouping And Command Substitution .......................10 More About Variable Substitution ..............................11 Substitution And Grouping Summary ........................11 Fine Points .................................................................12 Comments .................................................................13 Command Line Arguments .........................................13 Reference ...................................................................14 Backslash Sequences ...........................................14 Arithmetic Operators ...........................................14 Built-in Math Functions ......................................15 Core Tcl Commands .............................................15 Predefined Variables ............................................18 2. Strings and Pattern Matching ......................... 19 The string Command ..................................................19 Strings And Expresssions ...........................................20 The append Command ...............................................21 The format Command ................................................21 The scan Command ...................................................23 String Matching .........................................................24 Regular Expressions ..................................................25 The regexp Command ................................................26 The regsub Command ................................................28 Created: May 9, 1994 —bookTOC.doc—Copyright Prentice Hall—DRAFT: 1/13/95 ii 3. Tcl Data Structures .........................................29 More About Variables .................................................29 The unset command ............................................30 Using info to find out about variables ...................30 Tcl Lists .....................................................................31 Constructing Lists: list, lappend, and concat ..............32 Getting List Elements: llength, lindex, and lrange .......33 Modifying Lists: linsert and lreplace ...........................34 Searching Lists: lsearch .............................................34 Sorting Lists: lsort ......................................................35 The split And join Commands ....................................35 Arrays ........................................................................36 The array Command ..................................................37 Environment Variables ...............................................38 Tracing Variable Values .............................................39 4. Control Flow Commands .................................41 If Then Else ................................................................42 Switch ........................................................................43 Foreach ......................................................................44 While .........................................................................45 For .............................................................................46 Break And Continue ...................................................46 Catch .........................................................................46 Error ..........................................................................48 Return .......................................................................49 5. Procedures and Scope .....................................51 The proc Command ....................................................51 Changing command names with rename ....................52 Scope .........................................................................53 The global Command .................................................53 Use Arrays for Global State ........................................55 Call By Name Using upvar ..........................................55 Passing arrays by name .......................................56 The uplevel Command ................................................57 6. Eval ................................................................59 Eval And List .............................................................59 Created: May 9, 1994 —bookTOC.doc—Copyright Prentice Hall—DRAFT: 1/13/95 iii Eval And Concat ........................................................61 Double-quotes and eval .......................................62 Commands That Concat Their Arguments ..................62 The subst Command ..................................................63 7. Working with UNIX ......................................... 65 Running Unix Programs With exec .............................65 auto_noexec .........................................................67 Looking At The File System ........................................67 Input/Output ............................................................70 Opening Files For I/O ................................................70 Reading And Writing ..................................................72 The puts and gets commands ..............................72 The read command ..............................................73 Random access I/O .............................................73 Closing I/O streams .............................................74 The Current Directory - cd And pwd ...........................74 Matching File Names With glob ..................................74 The exit And pid commands .......................................75 8. Reflection and Debugging ............................... 77 The info Command .....................................................77 Variables .............................................................78 Procedures ...........................................................79 The call stack ......................................................79 Command evaluation ...........................................80 Scripts and the library .........................................80 Version numbers .................................................80 Interactive Command History .....................................81 History syntax .....................................................82 A comparision to /bin/csh history syntax ............ 82 Debugging ..................................................................83 Don Libes’ debugger ...................................................84 Breakpoints by pattern matching .........................85 Deleting break points ...........................................86 The tkerror Command ................................................87 The tkinspect Program ...............................................87 Performance Tuning ...................................................87 Created: May 9, 1994 —bookTOC.doc—Copyright Prentice Hall—DRAFT: 1/13/95 iv 9. Script Libraries ...............................................89 The unknown Command ............................................89 The tclIndex File .........................................................90 Using A Library: auto_path .........................................90 Disabling the library facility: auto_noload ............91 How Auto Loading Works ...........................................91 Interactive Conveniences ............................................92 Auto Execute .......................................................92 History .................................................................92 Abbreviations .......................................................92 Tcl Shell Library Environment ....................................93 Coding Style ...............................................................93 A module prefix for procedure names ...................94 A global array for state variables ..........................94 10. Tk Fundamentals ..........................................95 Hello World In Tk .......................................................96 Naming Tk Widgets ....................................................98 Configuring Tk Widgets ..............................................98 About The Tk Man Pages ............................................99
Recommended publications
  • C++ Programming: Program Design Including Data Structures, Fifth Edition
    C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: • Learn about repetition (looping) control structures • Explore how to construct and use count- controlled, sentinel-controlled, flag- controlled, and EOF-controlled repetition structures • Examine break and continue statements • Discover how to form and use nested control structures C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2 Objectives (cont'd.) • Learn how to avoid bugs by avoiding patches • Learn how to debug loops C++ Programming: From Problem Analysis to Program Design, Fifth Edition 3 Why Is Repetition Needed? • Repetition allows you to efficiently use variables • Can input, add, and average multiple numbers using a limited number of variables • For example, to add five numbers: – Declare a variable for each number, input the numbers and add the variables together – Create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers C++ Programming: From Problem Analysis to Program Design, Fifth Edition 4 while Looping (Repetition) Structure • The general form of the while statement is: while is a reserved word • Statement can be simple or compound • Expression acts as a decision maker and is usually a logical expression • Statement is called the body of the loop • The parentheses are part of the syntax C++ Programming: From Problem Analysis to Program Design, Fifth Edition 5 while Looping (Repetition)
    [Show full text]
  • Java Programming Standards & Reference Guide
    Java Programming Standards & Reference Guide Version 3.2 Office of Information & Technology Department of Veterans Affairs Java Programming Standards & Reference Guide, Version 3.2 REVISION HISTORY DATE VER. DESCRIPTION AUTHOR CONTRIBUTORS 10-26-15 3.2 Added Logging Sid Everhart JSC Standards , updated Vic Pezzolla checkstyle installation instructions and package name rules. 11-14-14 3.1 Added ground rules for Vic Pezzolla JSC enforcement 9-26-14 3.0 Document is continually Raymond JSC and several being edited for Steele OI&T noteworthy technical accuracy and / PD Subject Matter compliance to JSC Experts (SMEs) standards. 12-1-09 2.0 Document Updated Michael Huneycutt Sr 4-7-05 1.2 Document Updated Sachin Mai L Vo Sharma Lyn D Teague Rajesh Somannair Katherine Stark Niharika Goyal Ron Ruzbacki 3-4-05 1.0 Document Created Sachin Sharma i Java Programming Standards & Reference Guide, Version 3.2 ABSTRACT The VA Java Development Community has been establishing standards, capturing industry best practices, and applying the insight of experienced (and seasoned) VA developers to develop this “Java Programming Standards & Reference Guide”. The Java Standards Committee (JSC) team is encouraging the use of CheckStyle (in the Eclipse IDE environment) to quickly scan Java code, to locate Java programming standard errors, find inconsistencies, and generally help build program conformance. The benefits of writing quality Java code infused with consistent coding and documentation standards is critical to the efforts of the Department of Veterans Affairs (VA). This document stands for the quality, readability, consistency and maintainability of code development and it applies to all VA Java programmers (including contractors).
    [Show full text]
  • Devsecops in Reguated Industries Capgemini Template.Indd
    DEVSECOPS IN REGULATED INDUSTRIES ACCELERATING SOFTWARE RELIABILITY & COMPLIANCE TABLE OF CONTENTS 03... Executive Summary 04... Introduction 07... Impediments to DevSecOps Adoption 10... Playbook for DevSecOps Adoption 19... Conclusion EXECUTIVE SUMMARY DevOps practices enable rapid product engineering delivery and operations, particularly by agile teams using lean practices. There is an evolution from DevOps to DevSecOps, which is at the intersection of development, operations, and security. Security cannot be added after product development is complete and security testing cannot be done as a once-per-release cycle activity. Shifting security Left implies integration of security at all stages of the Software Development Life Cycle (SDLC). Adoption of DevSecOps practices enables faster, more reliable and more secure software. While DevSecOps emerged from Internet and software companies, it can benefit other industries, including regulated and high security environments. This whitepaper covers how incorporating DevSecOps in regulated Industries can accelerate software delivery, reducing the time from code change to production deployment or release while reducing security risks. This whitepaper defines a playbook for DevSecOps goals, addresses challenges, and discusses evolving workflows in DevSecOps, including cloud, agile, application modernization and digital transformation. Bi-directional requirement traceability, document generation and security tests should be part of the CI/CD pipeline. Regulated industries can securely move away
    [Show full text]
  • 7. Control Flow First?
    Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 Ordering Program Execution: What is Done 7. Control Flow First? Overview Categories for specifying ordering in programming languages: Expressions 1. Sequencing: the execution of statements and evaluation of Evaluation order expressions is usually in the order in which they appear in a Assignments program text Structured and unstructured flow constructs 2. Selection (or alternation): a run-time condition determines the Goto's choice among two or more statements or expressions Sequencing 3. Iteration: a statement is repeated a number of times or until a Selection run-time condition is met Iteration and iterators 4. Procedural abstraction: subroutines encapsulate collections of Recursion statements and subroutine calls can be treated as single Nondeterminacy statements 5. Recursion: subroutines which call themselves directly or indirectly to solve a problem, where the problem is typically defined in terms of simpler versions of itself 6. Concurrency: two or more program fragments executed in parallel, either on separate processors or interleaved on a single processor Note: Study Chapter 6 of the textbook except Section 7. Nondeterminacy: the execution order among alternative 6.6.2. constructs is deliberately left unspecified, indicating that any alternative will lead to a correct result Expression Syntax Expression Evaluation Ordering: Precedence An expression consists of and Associativity An atomic object, e.g. number or variable The use of infix, prefix, and postfix notation leads to ambiguity An operator applied to a collection of operands (or as to what is an operand of what arguments) which are expressions Fortran example: a+b*c**d**e/f Common syntactic forms for operators: The choice among alternative evaluation orders depends on Function call notation, e.g.
    [Show full text]
  • While Statement in C
    While Statement In C EnricoIs Reg alwaysdisheartening deplete or his novel aspects when chagrined luminesced disputatiously, some crayfishes he orbits clump so temporizingly? grindingly. Solid Ring-necked and comose Bennet Brendan tarnishes never tensehalf-and-half his Stuttgart! while Thank you use a counter is a while loop obscures the condition which is evaluated to embed videos in while c program C while loops statement allows to repeatedly run at same recipient of code until a wrap is met while loop is empty most basic loop in C programming while loop. We then hand this variable c in the statement block and represent your value for each. While adultery in C Set of instructions given coil the compiler to night set of statements until condition becomes false is called loops. If it is negative number added to the condition in c language including but in looping structures, but is executed infinite loop! While Loop Definition Example & Results Video & Lesson. While talking in C Know Program. What is the while eternal in C? A while loop around loop continuously and infinitely until the policy inside the parenthesis becomes false money must guard the. C while and dowhile Loop Programiz. Programming While Loop. The widow while redeem in the C language is basically a post tested loop upon the execution of several parts of the statements can be repeated by reckless use children do-while. 43 Loops Applications in C for Engineering Technology. Do it Loop in C Programming with Examples Phptpoint. Statements and display control C Tutorials Cpluspluscom. Do while just in c example program.
    [Show full text]
  • Chapter 6 Flow of Control
    Chapter 6 Flow of Control 6.1 INTRODUCTION “Don't you hate code that's In Figure 6.1, we see a bus carrying the children to not properly indented? school. There is only one way to reach the school. The Making it [indenting] part of driver has no choice, but to follow the road one milestone the syntax guarantees that all after another to reach the school. We learnt in Chapter code is properly indented.” 5 that this is the concept of sequence, where Python executes one statement after another from beginning to – G. van Rossum the end of the program. These are the kind of programs we have been writing till now. In this chapter Figure 6.1: Bus carrying students to school » Introduction to Flow of Control Let us consider a program 6-1 that executes in » Selection sequence, that is, statements are executed in an order in which they are written. » Indentation The order of execution of the statements in a program » Repetition is known as flow of control. The flow of control can be » Break and Continue implemented using control structures. Python supports Statements two types of control structures—selection and repetition. » Nested Loops 2021-22 Ch 6.indd 121 08-Apr-19 12:37:51 PM 122 COMPUTER SCIENCE – CLASS XI Program 6-1 Program to print the difference of two numbers. #Program 6-1 #Program to print the difference of two input numbers num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) diff = num1 - num2 print("The difference of",num1,"and",num2,"is",diff) Output: Enter first number 5 Enter second number 7 The difference of 5 and 7 is -2 6.2 SELECTION Now suppose we have `10 to buy a pen.
    [Show full text]
  • While and Do-While Loops
    While and Do-While Loops 15-110 Summer 2010 Margaret Reid-Miller Loops • Within a method, we can alter the flow of control using either conditionals or loops. • The loop statements while, do-while, and for allow us execute a statement(s) over and over. • Like a conditional, a loop is controlled by a boolean expression that determines how many times the statement is executed. E.g., You may want to calculate the interest paid on a mortgage for each year of the loan term. Summer 2010 15-110 (Reid-Miller) The while statement • The form of the while statement is while (<boolean_expression>) <statement> • If boolean_expression evaluates to true, then statement is executed. • Then, the boolean_expression is evaluated again. If it evaluates to true, statement is executed again. • This repetition continues until the boolean_expression evaluates to false. How is the while loop different from the if statement? Summer 2010 15-110 (Reid-Miller) The if Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) The while Flowchart false boolean_expression true statement (body of loop) Summer 2010 15-110 (Reid-Miller) A Example n = 5 while i output 0 Print n asterisks! i < n ? *! 1 int i = 0; ! i < n ? while (i < n) { ! ! **! System.out.print(“*”);! 2 i < n ? !i++;! ***! }! 3 i < n ? System.out.println();! ****! 4 i < n ? *****! 5 i < n ? ***** Summer 2010 15-110 (Reid-Miller) The Loop Control Variable • The variable i (known as the loop control variable) is used in three ways: it is initialized, tested, and updated.!
    [Show full text]
  • Chapter 5: Conditionals and Loops Lab Exercises
    Chapter 5: Conditionals and Loops Lab Exercises Topics Lab Exercises Boolean expressions PreLab Exercises The if statement Computing a Raise The switch statement A Charge Account Statement Activities at Lake LazyDays Rock, Paper, Scissors Date Validation Conditional Operator Processing Grades The while statement PreLab Exercises Counting and Looping Powers of 2 Factorials A Guessing Game Iterators & Reading Text Files Baseball Statistics The do statement More Guessing Election Day The for statement Finding Maximum and Minimum Values Counting Characters Using the Coin Class Drawing with loops and conditionals A Rainbow Program Determining Event Sources Vote Counter, Revisited Dialog Boxes Modifying EvenOdd.java A Pay Check Program Checkboxes & Radio Buttons Adding Buttons to StyleOptions.java Chapter 5: Conditionals and Loops 65 Prelab Exercises Sections 5.1-5.3 1. Rewrite each condition below in valid Java syntax (give a boolean expression): a. x > y > z b. x and y are both less than 0 c. neither x nor y is less than 0 d. x is equal to y but not equal to z 2. Suppose gpa is a variable containing the grade point average of a student. Suppose the goal of a program is to let a student know if he/she made the Dean's list (the gpa must be 3.5 or above). Write an if... else... statement that prints out the appropriate message (either "Congratulations—you made the Dean's List" or "Sorry you didn't make the Dean's List"). 3. Complete the following program to determine the raise and new salary for an employee by adding if ..
    [Show full text]
  • PYTHON LOOPS Rialspo Int.Co M/Pytho N/Pytho N Lo O Ps.Htm Copyrig Ht © Tutorialspoint.Com
    PYTHON LOOPS http://www.tuto rialspo int.co m/pytho n/pytho n_lo o ps.htm Copyrig ht © tutorialspoint.com There may be a situation when you need to execute a block of code several number of times. In g eneral, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Prog ramming lang uag es provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or g roup of statements multiple times and following is the g eneral form of a loop statement in most of the prog ramming lang uag es: Python prog ramming lang uag e provides following types of loops to handle looping requirements. Click the following links to check their detail. Loop Type Description while loop Repeats a statement or g roup of statements while a g iven condition is true. It tests the condition before executing the loop body. for loop Executes a sequence of statements multiple times and abbreviates the code that manag es the loop variable. nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements: Loop control statements chang e execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. Control Statement Description break statement Terminates the loop statement and transfers execution to the statement immediately following the loop.
    [Show full text]
  • Smalltalk Tutorial for Java Programmers!
    SmallTalk Tutorial for Java Programmers! SmallTalk Tutorial for Java Programmers! Giovanni Giorgi <[email protected]> Jan 2002 A small paper to teach yourself the incredible Smalltalk language! It's so easy, it's so fun! 1. Introduction ● 1.1 Revision history ● 1.2 Conventions used in this paper ● 1.3 Distribution Policy ● 1.4 Why Smalltalk? ● 1.5 Background Required 2. Why Smalltalk is so strange? (or a brief history of Smalltalk) ● 2.1 Download Right Now! ● 2.2 Hello world in Smalltalk ● 2.3 Big Numbers ● 2.4 Code Blocks ● 2.5 The while loop 3. Main Differences between Java and Smalltalk http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (1 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers! ● 3.1 Java Versus Smalltalk ● 3.2 Types? No thank you!! ● 3.3 The Squeak base library compared with Java ● 3.4 The Smalltalk Code database ● 3.5 Multiple-Inheritance 4. Ending Words ● 4.1 Going on ● 4.2 Commercial and free products list ● 4.3 References http://daitanmarks.sourceforge.net/or/squeak/squeak_tutorial.html (2 of 2) [1/7/2002 20:44:13] SmallTalk Tutorial for Java Programmers!: Introduction 1. Introduction This paper will teach you the basics of Smalltalk80 language. This tutorial suites the needs of C and Java programmers. But the tutorial can be understanded by everyone knowing a bit of C and/or OOP concepts, as we'll see. Because I will refer a lot to other books and use a lot of technical terms, I'll try to enjoy you while reading.
    [Show full text]
  • Advanced Tcl E D
    PART II I I . A d v a n c Advanced Tcl e d T c l Part II describes advanced programming techniques that support sophisticated applications. The Tcl interfaces remain simple, so you can quickly construct pow- erful applications. Chapter 10 describes eval, which lets you create Tcl programs on the fly. There are tricks with using eval correctly, and a few rules of thumb to make your life easier. Chapter 11 describes regular expressions. This is the most powerful string processing facility in Tcl. This chapter includes a cookbook of useful regular expressions. Chapter 12 describes the library and package facility used to organize your code into reusable modules. Chapter 13 describes introspection and debugging. Introspection provides information about the state of the Tcl interpreter. Chapter 14 describes namespaces that partition the global scope for vari- ables and procedures. Namespaces help you structure large Tcl applications. Chapter 15 describes the features that support Internationalization, includ- ing Unicode, other character set encodings, and message catalogs. Chapter 16 describes event-driven I/O programming. This lets you run pro- cess pipelines in the background. It is also very useful with network socket pro- gramming, which is the topic of Chapter 17. Chapter 18 describes TclHttpd, a Web server built entirely in Tcl. You can build applications on top of TclHttpd, or integrate the server into existing appli- cations to give them a web interface. TclHttpd also supports regular Web sites. Chapter 19 describes Safe-Tcl and using multiple Tcl interpreters. You can create multiple Tcl interpreters for your application. If an interpreter is safe, then you can grant it restricted functionality.
    [Show full text]
  • C Programming Tutorial
    C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at [email protected] ii Table of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ............................................................................................ 3 Installation on Unix/Linux ............................................................................
    [Show full text]