Synopses & Reviews
The Perl Cookbook is a comprehensive collection of problems, solutions, and practical examples for anyone programming in Perl. Topics range from beginner questions to techniques that even the most experienced of Perl programmers will learn from. More than just a collection of tips and tricks, the Perl Cookbook is the long-awaited companion volume to Programming Perl, filled with previously unpublished Perl arcana.The Perl Cookbook contains thousands upon thousands of examples ranging from brief one-liners to complete applications. Covered topic areas spread across nearly four hundred separate "recipes," including:
- Manipulation of strings, numbers, dates, arrays, and hashes
- Reading, writing, and updating text and binary files
- Pattern matching and text substitutions
- Subroutines, libraries, and modules
- References, data structures, objects, and classes
- Signals and exceptions
- Accessing text, hashes, and SQL databases
- Screen addressing, menus, and graphical applications
- Managing other processes
- Writing secure scripts
- Client-server programming
- Internet applications programming with mail, news, ftp, and telnet
These recipes were rigorously reviewed by scores of the best minds inside and outside Perl, foremost of which was Larry Wall, the creator of Perl himself.The Perl Cookbook
is written by Tom Christiansen, Perl evangelist and coauthor of the bestselling Programming Perl
and Learning Perl
; and Nathan Torkington, Perl trainer and co-maintainer of the Perl Frequently Asked Questions list.
"The Perl Cookbook" is a collection of hundreds of problems and their solutions (with examples) for anyone programming in Perl. The topics range from beginner questions to techniques that are helpful for even the most experienced Perl programmers.
This comprehensive collection of problems, solutions, and practical examples for anyone programming in Perl covers everything from beginner questions to techniques for even the most experienced Perl programmer. It contains hundreds of Perl "recipes" that were rigorously reviewed by scores of the best minds inside and outside of Perl, foremost of which was Larry Wall, the creator of Perl himself.
You'll find recipes for manipulating strings, numbers, dates, arrays, and hashes; pattern matching and text substitutions; references, data structures, objects, and classes; signals and exceptions; accessing text, hashes, and SQL databases; and managing other processes. You'll also uncover recipes for writing secure scripts; client-server programming; Internet applications programming with mail, news, ftp, and telnet; and CGI programming and Web automation.
About the Author
Tom Christiansen is a freelance consultant specializing in Perl training and writing. After working for several years for TSR Hobbies (of Dungeons and Dragons fame), he set off for college where he spent a year in Spain and five in America, dabbling in music, linguistics, programming, and some half-dozen different spoken languages. Tom finally escaped UW-Madison with B.A.s in Spanish and computer science and an M.S. in computer science. He then spent five years at Convex as a jack-of-all-trades working on everything from system administration to utility and kernel development, with customer support and training thrown in for good measure. Tom also served two terms on the USENIX Association Board of directors. With over fifteen years' experience in UNIX system administration and programming, Tom presents seminars internationally. Living in the foothills above Boulder, Colorado, surrounded by mule deer, skunks, and the occasional mountain lion and black bear, Tom takes summers off for hiking, hacking, birding, music making, and gaming.
Nathan Torkington is a banjo player, father, and husband. His crimes in the computing community include: coauthor of the Perl Cookbook, editor for O'Reilly and Associates, content coordinator for the Open Source Convention and Perl Conference, and project manager for perl6.
Table of Contents
List of Examples; Foreword; Preface; What's in This Book; Platform Notes; Other Books; Conventions Used in This Book; We'd Like to Hear from You; Acknowledgments; Chapter 1: Strings; 1.1 Introduction; 1.2 Accessing Substrings; 1.3 Establishing a Default Value; 1.4 Exchanging Values Without Using Temporary Variables; 1.5 Converting Between ASCII Characters and Values; 1.6 Processing a String One Character at a Time; 1.7 Reversing a String by Word or Character; 1.8 Expanding and Compressing Tabs; 1.9 Expanding Variables in User Input; 1.10 Controlling Case; 1.11 Interpolating Functions and Expressions Within Strings; 1.12 Indenting Here Documents; 1.13 Reformatting Paragraphs; 1.14 Escaping Characters; 1.15 Trimming Blanks from the Ends of a String; 1.16 Parsing Comma-Separated Data; 1.17 Soundex Matching; 1.18 Program: fixstyle; 1.19 Program: psgrep; Chapter 2: Numbers; 2.1 Introduction; 2.2 Checking Whether a String Is a Valid Number; 2.3 Comparing Floating-Point Numbers; 2.4 Rounding Floating-Point Numbers; 2.5 Converting Between Binary and Decimal; 2.6 Operating on a Series of Integers; 2.7 Working with Roman Numerals; 2.8 Generating Random Numbers; 2.9 Generating Different Random Numbers; 2.10 Making Numbers Even More Random; 2.11 Generating Biased Random Numbers; 2.12 Doing Trigonometry in Degrees, not Radians; 2.13 Calculating More Trigonometric Functions; 2.14 Taking Logarithms; 2.15 Multiplying Matrices; 2.16 Using Complex Numbers; 2.17 Converting Between Octal and Hexadecimal; 2.18 Putting Commas in Numbers; 2.19 Printing Correct Plurals; 2.20 Program: Calculating Prime Factors; Chapter 3: Dates and Times; 3.1 Introduction; 3.2 Finding Today's Date; 3.3 Converting DMYHMS to Epoch Seconds; 3.4 Converting Epoch Seconds to DMYHMS; 3.5 Adding to or Subtracting from a Date; 3.6 Difference of Two Dates; 3.7 Day in a Week/Month/Year or Week Number; 3.8 Parsing Dates and Times from Strings; 3.9 Printing a Date; 3.10 High-Resolution Timers; 3.11 Short Sleeps; 3.12 Program: hopdelta; Chapter 4: Arrays; 4.1 Introduction; 4.2 Specifying a List In Your Program; 4.3 Printing a List with Commas; 4.4 Changing Array Size; 4.5 Doing Something with Every Element in a List; 4.6 Iterating Over an Array by Reference; 4.7 Extracting Unique Elements from a List; 4.8 Finding Elements in One Array but Not Another; 4.9 Computing Union, Intersection, or Difference of Unique Lists; 4.10 Appending One Array to Another; 4.11 Reversing an Array; 4.12 Processing Multiple Elements of an Array; 4.13 Finding the First List Element That Passes a Test; 4.14 Finding All Elements in an Array Matching Certain Criteria; 4.15 Sorting an Array Numerically; 4.16 Sorting a List by Computable Field; 4.17 Implementing a Circular List; 4.18 Randomizing an Array; 4.19 Program: words; 4.20 Program: permute; Chapter 5: Hashes; 5.1 Introduction; 5.2 Adding an Element to a Hash; 5.3 Testing for the Presence of a Key in a Hash; 5.4 Deleting from a Hash; 5.5 Traversing a Hash; 5.6 Printing a Hash; 5.7 Retrieving from a Hash in Insertion Order; 5.8 Hashes with Multiple Values Per Key; 5.9 Inverting a Hash; 5.10 Sorting a Hash; 5.11 Merging Hashes; 5.12 Finding Common or Different Keys in Two Hashes; 5.13 Hashing References; 5.14 Presizing a Hash; 5.15 Finding the Most Common Anything; 5.16 Representing Relationships Between Data; 5.17 Program: dutree; Chapter 6: Pattern Matching; 6.1 Introduction; 6.2 Copying and Substituting Simultaneously; 6.3 Matching Letters; 6.4 Matching Words; 6.5 Commenting Regular Expressions; 6.6 Finding the Nth Occurrence of a Match; 6.7 Matching Multiple Lines; 6.8 Reading Records with a Pattern Separator; 6.9 Extracting a Range of Lines; 6.10 Matching Shell Globs as Regular Expressions; 6.11 Speeding Up Interpolated Matches; 6.12 Testing for a Valid Pattern; 6.13 Honoring Locale Settings in Regular Expressions; 6.14 Approximate Matching; 6.15 Matching from Where the Last Pattern Left Off; 6.16 Greedy and Non-Greedy Matches; 6.17 Detecting Duplicate Words; 6.18 Expressing AND, OR, and NOT in a Single Pattern; 6.19 Matching Multiple-Byte Characters; 6.20 Matching a Valid Mail Address; 6.21 Matching Abbreviations; 6.22 Program: urlify; 6.23 Program: tcgrep; 6.24 Regular Expression Grabbag; Chapter 7: File Access; 7.1 Introduction; 7.2 Opening a File; 7.3 Opening Files with Unusual Filenames; 7.4 Expanding Tildes in Filenames; 7.5 Making Perl Report Filenames in Errors; 7.6 Creating Temporary Files; 7.7 Storing Files Inside Your Program Text; 7.8 Writing a Filter; 7.9 Modifying a File in Place with Temporary File; 7.10 Modifying a File in Place with -i Switch; 7.11 Modifying a File in Place Without a Temporary File; 7.12 Locking a File; 7.13 Flushing Output; 7.14 Reading from Many Filehandles Without Blocking; 7.15 Doing Non-Blocking I/O; 7.16 Determining the Number of Bytes to Read; 7.17 Storing Filehandles in Variables; 7.18 Caching Open Output Filehandles; 7.19 Printing to Many Filehandles Simultaneously; 7.20 Opening and Closing File Descriptors by Number; 7.21 Copying Filehandles; 7.22 Program: netlock; 7.23 Program: lockarea; Chapter 8: File Contents; 8.1 Introduction; 8.2 Reading Lines with Continuation Characters; 8.3 Counting Lines (or Paragraphs or Records) in a File; 8.4 Processing Every Word in a File; 8.5 Reading a File Backwards by Line or Paragraph; 8.6 Trailing a Growing File; 8.7 Picking a Random Line from a File; 8.8 Randomizing All Lines; 8.9 Reading a Particular Line in a File; 8.10 Processing Variable-Length Text Fields; 8.11 Removing the Last Line of a File; 8.12 Processing Binary Files; 8.13 Using Random-Access I/O; 8.14 Updating a Random-Access File; 8.15 Reading a String from a Binary File; 8.16 Reading Fixed-Length Records; 8.17 Reading Configuration Files; 8.18 Testing a File for Trustworthiness; 8.19 Program: tailwtmp; 8.20 Program: tctee; 8.21 Program: laston; Chapter 9: Directories; 9.1 Introduction; 9.2 Getting and Setting Timestamps; 9.3 Deleting a File; 9.4 Copying or Moving a File; 9.5 Recognizing Two Names for the Same File; 9.6 Processing All Files in a Directory; 9.7 Globbing, or Getting a List of Filenames Matching a Pattern; 9.8 Processing All Files in a Directory Recursively; 9.9 Removing a Directory and Its Contents; 9.10 Renaming Files; 9.11 Splitting a Filename into Its Component Parts; 9.12 Program: symirror; 9.13 Program: lst; Chapter 10: Subroutines; 10.1 Introduction; 10.2 Accessing Subroutine Arguments; 10.3 Making Variables Private to a Function; 10.4 Creating Persistent Private Variables; 10.5 Determining Current Function Name; 10.6 Passing Arrays and Hashes by Reference; 10.7 Detecting Return Context; 10.8 Passing by Named Parameter; 10.9 Skipping Selected Return Values; 10.10 Returning More Than One Array or Hash; 10.11 Returning Failure; 10.12 Prototyping Functions; 10.13 Handling Exceptions; 10.14 Saving Global Values; 10.15 Redefining a Function; 10.16 Trapping Undefined Function Calls with AUTOLOAD; 10.17 Nesting Subroutines; 10.18 Program: Sorting Your Mail; Chapter 11: References and Records; 11.1 Introduction; 11.2 Taking References to Arrays; 11.3 Making Hashes of Arrays; 11.4 Taking References to Hashes; 11.5 Taking References to Functions; 11.6 Taking References to Scalars; 11.7 Creating Arrays of Scalar References; 11.8 Using Closures Instead of Objects; 11.9 Creating References to Methods; 11.10 Constructing Records; 11.11 Reading and Writing Hash Records to Text Files; 11.12 Printing Data Structures; 11.13 Copying Data Structures; 11.14 Storing Data Structures to Disk; 11.15 Transparently Persistent Data Structures; 11.16 Program: Binary Trees; Chapter 12: Packages, Libraries, and Modules; 12.1 Introduction; 12.2 Defining a Module's Interface; 12.3 Trapping Errors in require or use; 12.4 Delaying use Until Run Time; 12.5 Making Variables Private to a Module; 12.6 Determining the Caller's Package; 12.7 Automating Module Clean-Up; 12.8 Keeping Your Own Module Directory; 12.9 Preparing a Module for Distribution; 12.10 Speeding Module Loading with SelfLoader; 12.11 Speeding Up Module Loading with Autoloader; 12.12 Overriding Built-In Functions; 12.13 Reporting Errors and Warnings Like Built-Ins; 12.14 Referring to Packages Indirectly; 12.15 Using h2ph to Translate C #include Files; 12.16 Using h2xs to Make a Module with C Code; 12.17 Documenting Your Module with Pod; 12.18 Building and Installing a CPAN Module; 12.19 Example: Module Template; 12.20 Program: Finding Versions and Descriptions of Installed Modules; Chapter 13: Classes, Objects, and Ties; 13.1 Introduction; 13.2 Constructing an Object; 13.3 Destroying an Object; 13.4 Managing Instance Data; 13.5 Managing Class Data; 13.6 Using Classes as Structs; 13.7 Cloning Objects; 13.8 Calling Methods Indirectly; 13.9 Determining Subclass Membership; 13.10 Writing an Inheritable Class; 13.11 Accessing Overridden Methods; 13.12 Generating Attribute Methods Using AUTOLOAD; 13.13 Solving the Data Inheritance Problem; 13.14 Coping with Circular Data Structures; 13.15 Overloading Operators; 13.16 Creating Magic Variables with tie; Chapter 14: Database Access; 14.1 Introduction; 14.2 Making and Using a DBM File; 14.3 Emptying a DBM File; 14.4 Converting Between DBM Files; 14.5 Merging DBM Files; 14.6 Locking DBM Files; 14.7 Sorting Large DBM Files; 14.8 Treating a Text File as a Database Array; 14.9 Storing Complex Data in a DBM File; 14.10 Persistent Data; 14.11 Executing an SQL Command Using DBI and DBD; 14.12 Program: ggh--Grep Netscape Global History; Chapter 15: User Interfaces; 15.1 Introduction; 15.2 Parsing Program Arguments; 15.3 Testing Whether a Program Is Running Interactively; 15.4 Clearing the Screen; 15.5 Determining Terminal or Window Size; 15.6 Changing Text Color; 15.7 Reading from the Keyboard; 15.8 Ringing the Terminal Bell; 15.9 Using POSIX termios; 15.10 Checking for Waiting Input; 15.11 Reading Passwords; 15.12 Editing Input; 15.13 Managing the Screen; 15.14 Controlling Another Program with Expect; 15.15 Creating Menus with Tk; 15.16 Creating Dialog Boxes with Tk; 15.17 Responding to Tk Resize Events; 15.18 Removing the DOS Shell Window with Windows Perl/Tk; 15.19 Program: Small termcap program; 15.20 Program: tkshufflepod; Chapter 16: Process Management and Communication; 16.1 Introduction; 16.2 Gathering Output from a Program; 16.3 Running Another Program; 16.4 Replacing the Current Program with a Different One; 16.5 Reading or Writing to Another Program; 16.6 Filtering Your Own Output; 16.7 Preprocessing Input; 16.8 Reading STDERR from a Program; 16.9 Controlling Input and Output of Another Program; 16.10 Controlling the Input, Output, and Error of Another Program; 16.11 Communicating Between Related Processes; 16.12 Making a Process Look Like a File with Named Pipes; 16.13 Sharing Variables in Different Processes; 16.14 Listing Available Signals; 16.15 Sending a Signal; 16.16 Installing a Signal Handler; 16.17 Temporarily Overriding a Signal Handler; 16.18 Writing a Signal Handler; 16.19 Catching Ctrl-C; 16.20 Avoiding Zombie Processes; 16.21 Blocking Signals; 16.22 Timing Out an Operation; 16.23 Program: sigrand; Chapter 17: Sockets; 17.1 Introduction; 17.2 Writing a TCP Client; 17.3 Writing a TCP Server; 17.4 Communicating over TCP; 17.5 Setting Up a UDP Client; 17.6 Setting Up a UDP Server; 17.7 Using UNIX Domain Sockets; 17.8 Identifying the Other End of a Socket; 17.9 Finding Your Own Name and Address; 17.10 Closing a Socket After Forking; 17.11 Writing Bidirectional Clients; 17.12 Forking Servers; 17.13 Pre-Forking Servers; 17.14 Non-Forking Servers; 17.15 Writing a Multi-Homed Server; 17.16 Making a Daemon Server; 17.17 Restarting a Server on Demand; 17.18 Program: backsniff; 17.19 Program: fwdport; Chapter 18: Internet Services; 18.1 Introduction; 18.2 Simple DNS Lookups; 18.3 Being an FTP Client; 18.4 Sending Mail; 18.5 Reading and Posting Usenet News Messages; 18.6 Reading Mail with POP3; 18.7 Simulating Telnet from a Program; 18.8 Pinging a Machine; 18.9 Using Whois to Retrieve Information from the InterNIC; 18.10 Program: expn and vrfy; Chapter 19: CGI Programming; 19.1 Introduction; 19.2 Writing a CGI Script; 19.3 Redirecting Error Messages; 19.4 Fixing a 500 Server Error; 19.5 Writing a Safe CGI Program; 19.6 Making CGI Scripts Efficient; 19.7 Executing Commands Without Shell Escapes; 19.8 Formatting Lists and Tables with HTML Shortcuts; 19.9 Redirecting to a Different Location; 19.10 Debugging the Raw HTTP Exchange; 19.11 Managing Cookies; 19.12 Creating Sticky Widgets; 19.13 Writing a Multiscreen CGI Script; 19.14 Saving a Form to a File or Mail Pipe; 19.15 Program: chemiserie; Chapter 20: Web Automation; 20.1 Introduction; 20.2 Fetching a URL from a Perl Script; 20.3 Automating Form Submission; 20.4 Extracting URLs; 20.5 Converting ASCII to HTML; 20.6 Converting HTML to ASCII; 20.7 Extracting or Removing HTML Tags; 20.8 Finding Stale Links; 20.9 Finding Fresh Links; 20.10 Creating HTML Templates; 20.11 Mirroring Web Pages; 20.12 Creating a Robot; 20.13 Parsing a Web Server Log File; 20.14 Processing Server Logs; 20.15 Program: htmlsub; 20.16 Program: hrefsub; Colophon;