O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Perl Cookbook, 2nd Edition

Book Description

Find a Perl programmer, and you'll find a copy of Perl Cookbook nearby. Perl Cookbook is a comprehensive collection of problems, solutions, and practical examples for anyone programming in Perl. The book contains hundreds of rigorously reviewed Perl "recipes" and thousands of examples ranging from brief one-liners to complete applications.The second edition of Perl Cookbook has been fully updated for Perl 5.8, with extensive changes for Unicode support, I/O layers, mod_perl, and new technologies that have emerged since the previous edition of the book. Recipes have been updated to include the latest modules. New recipes have been added to every chapter of the book, and some chapters have almost doubled in size.Covered topic areas include:

  • Manipulating strings, numbers, dates, arrays, and hashes
  • Pattern matching and text substitutions
  • References, data structures, objects, and classes
  • Signals and exceptions
  • Screen addressing, menus, and graphical applications
  • Managing other processes
  • Writing secure scripts
  • Client-server programming
  • Internet applications programming with mail, news, ftp, and telnet
  • CGI and mod_perl programming
  • Web programming
Since its first release in 1998, Perl Cookbook has earned its place in the libraries of serious Perl users of all levels of expertise by providing practical answers, code examples, and mini-tutorials addressing the challenges that programmers face. Now the second edition of this bestselling book is ready to earn its place among the ranks of favorite Perl books as well.Whether you're a novice or veteran Perl programmer, you'll find Perl Cookbook, 2nd Edition to be one of the most useful books on Perl available. Its comfortable discussion style and accurate attention to detail cover just about any topic you'd want to know about. You can get by without having this book in your library, but once you've tried a few of the recipes, you won't want to.

Table of Contents

  1. A Note Regarding Supplemental Files
  2. Foreword
  3. Preface
    1. What’s in This Book
    2. What’s New in This Edition
    3. Platform Notes
    4. Other Books
    5. Conventions Used in This Book
    6. We’d Like to Hear from You
    7. Acknowledgments for the First Edition
    8. Acknowledgments for the Second Edition
  4. 1. Strings
    1. Introduction
    2. 1.1. Accessing Substrings
    3. 1.2. Establishing a Default Value
    4. 1.3. Exchanging Values Without Using Temporary Variables
    5. 1.4. Converting Between Characters and Values
    6. 1.5. Using Named Unicode Characters
    7. 1.6. Processing a String One Character at a Time
    8. 1.7. Reversing a String by Word or Character
    9. 1.8. Treating Unicode Combined Characters as Single Characters
    10. 1.9. Canonicalizing Strings with Unicode Combined Characters
    11. 1.10. Treating a Unicode String as Octets
    12. 1.11. Expanding and Compressing Tabs
    13. 1.12. Expanding Variables in User Input
    14. 1.13. Controlling Case
    15. 1.14. Properly Capitalizing a Title or Headline
    16. 1.15. Interpolating Functions and Expressions Within Strings
    17. 1.16. Indenting Here Documents
    18. 1.17. Reformatting Paragraphs
    19. 1.18. Escaping Characters
    20. 1.19. Trimming Blanks from the Ends of a String
    21. 1.20. Parsing Comma-Separated Data
    22. 1.21. Constant Variables
    23. 1.22. Soundex Matching
    24. 1.23. Program: fixstyle
    25. 1.24. Program: psgrep
  5. 2. Numbers
    1. Introduction
    2. 2.1. Checking Whether a String Is a Valid Number
    3. 2.2. Rounding Floating-Point Numbers
    4. 2.3. Comparing Floating-Point Numbers
    5. 2.4. Operating on a Series of Integers
    6. 2.5. Working with Roman Numerals
    7. 2.6. Generating Random Numbers
    8. 2.7. Generating Repeatable Random Number Sequences
    9. 2.8. Making Numbers Even More Random
    10. 2.9. Generating Biased Random Numbers
    11. 2.10. Doing Trigonometry in Degrees, Not Radians
    12. 2.11. Calculating More Trigonometric Functions
    13. 2.12. Taking Logarithms
    14. 2.13. Multiplying Matrices
    15. 2.14. Using Complex Numbers
    16. 2.15. Converting Binary, Octal, and Hexadecimal Numbers
    17. 2.16. Putting Commas in Numbers
    18. 2.17. Printing Correct Plurals
    19. 2.18. Program: Calculating Prime Factors
  6. 3. Dates and Times
    1. Introduction
    2. 3.1. Finding Today’s Date
    3. 3.2. Converting DMYHMS to Epoch Seconds
    4. 3.3. Converting Epoch Seconds to DMYHMS
    5. 3.4. Adding to or Subtracting from a Date
    6. 3.5. Difference of Two Dates
    7. 3.6. Day in a Week/Month/Year or Week Number
    8. 3.7. Parsing Dates and Times from Strings
    9. 3.8. Printing a Date
    10. 3.9. High-Resolution Timers
    11. 3.10. Short Sleeps
    12. 3.11. Program: hopdelta
  7. 4. Arrays
    1. Introduction
    2. 4.1. Specifying a List in Your Program
    3. 4.2. Printing a List with Commas
    4. 4.3. Changing Array Size
    5. 4.4. Implementing a Sparse Array
    6. 4.5. Iterating Over an Array
    7. 4.6. Iterating Over an Array by Reference
    8. 4.7. Extracting Unique Elements from a List
    9. 4.8. Finding Elements in One Array but Not Another
    10. 4.9. Computing Union, Intersection, or Difference of Unique Lists
    11. 4.10. Appending One Array to Another
    12. 4.11. Reversing an Array
    13. 4.12. Processing Multiple Elements of an Array
    14. 4.13. Finding the First List Element That Passes a Test
    15. 4.14. Finding All Elements in an Array Matching Certain Criteria
    16. 4.15. Sorting an Array Numerically
    17. 4.16. Sorting a List by Computable Field
    18. 4.17. Implementing a Circular List
    19. 4.18. Randomizing an Array
    20. 4.19. Program: words
    21. 4.20. Program: permute
  8. 5. Hashes
    1. Introduction
    2. 5.1. Adding an Element to a Hash
    3. 5.2. Testing for the Presence of a Key in a Hash
    4. 5.3. Creating a Hash with Immutable Keys or Values
    5. 5.4. Deleting from a Hash
    6. 5.5. Traversing a Hash
    7. 5.6. Printing a Hash
    8. 5.7. Retrieving from a Hash in Insertion Order
    9. 5.8. Hashes with Multiple Values per Key
    10. 5.9. Inverting a Hash
    11. 5.10. Sorting a Hash
    12. 5.11. Merging Hashes
    13. 5.12. Finding Common or Different Keys in Two Hashes
    14. 5.13. Hashing References
    15. 5.14. Presizing a Hash
    16. 5.15. Finding the Most Common Anything
    17. 5.16. Representing Relationships Between Data
    18. 5.17. Program: dutree
  9. 6. Pattern Matching
    1. Introduction
    2. 6.1. Copying and Substituting Simultaneously
    3. 6.2. Matching Letters
    4. 6.3. Matching Words
    5. 6.4. Commenting Regular Expressions
    6. 6.5. Finding the Nth Occurrence of a Match
    7. 6.6. Matching Within Multiple Lines
    8. 6.7. Reading Records with a Separator
    9. 6.8. Extracting a Range of Lines
    10. 6.9. Matching Shell Globs as Regular Expressions
    11. 6.10. Speeding Up Interpolated Matches
    12. 6.11. Testing for a Valid Pattern
    13. 6.12. Honoring Locale Settings in Regular Expressions
    14. 6.13. Approximate Matching
    15. 6.14. Matching from Where the Last Pattern Left Off
    16. 6.15. Greedy and Non-Greedy Matches
    17. 6.16. Detecting Doubled Words
    18. 6.17. Matching Nested Patterns
    19. 6.18. Expressing AND, OR, and NOT in a Single Pattern
    20. 6.19. Matching a Valid Mail Address
    21. 6.20. Matching Abbreviations
    22. 6.21. Program: urlify
    23. 6.22. Program: tcgrep
    24. 6.23. Regular Expression Grab Bag
  10. 7. File Access
    1. Introduction
    2. 7.1. Opening a File
    3. 7.2. Opening Files with Unusual Filenames
    4. 7.3. Expanding Tildes in Filenames
    5. 7.4. Making Perl Report Filenames in Error Messages
    6. 7.5. Storing Filehandles into Variables
    7. 7.6. Writing a Subroutine That Takes Filehandles as Built-ins Do
    8. 7.7. Caching Open Output Filehandles
    9. 7.8. Printing to Many Filehandles Simultaneously
    10. 7.9. Opening and Closing File Descriptors by Number
    11. 7.10. Copying Filehandles
    12. 7.11. Creating Temporary Files
    13. 7.12. Storing a File Inside Your Program Text
    14. 7.13. Storing Multiple Files in the DATA Area
    15. 7.14. Writing a Unix-Style Filter Program
    16. 7.15. Modifying a File in Place with a Temporary File
    17. 7.16. Modifying a File in Place with the -i Switch
    18. 7.17. Modifying a File in Place Without a Temporary File
    19. 7.18. Locking a File
    20. 7.19. Flushing Output
    21. 7.20. Doing Non-Blocking I/O
    22. 7.21. Determining the Number of Unread Bytes
    23. 7.22. Reading from Many Filehandles Without Blocking
    24. 7.23. Reading an Entire Line Without Blocking
    25. 7.24. Program: netlock
    26. 7.25. Program: lockarea
  11. 8. File Contents
    1. Introduction
    2. 8.1. Reading Lines with Continuation Characters
    3. 8.2. Counting Lines (or Paragraphs or Records) in a File
    4. 8.3. Processing Every Word in a File
    5. 8.4. Reading a File Backward by Line or Paragraph
    6. 8.5. Trailing a Growing File
    7. 8.6. Picking a Random Line from a File
    8. 8.7. Randomizing All Lines
    9. 8.8. Reading a Particular Line in a File
    10. 8.9. Processing Variable-Length Text Fields
    11. 8.10. Removing the Last Line of a File
    12. 8.11. Processing Binary Files
    13. 8.12. Using Random-Access I/O
    14. 8.13. Updating a Random-Access File
    15. 8.14. Reading a String from a Binary File
    16. 8.15. Reading Fixed-Length Records
    17. 8.16. Reading Configuration Files
    18. 8.17. Testing a File for Trustworthiness
    19. 8.18. Treating a File as an Array
    20. 8.19. Setting the Default I/O Layers
    21. 8.20. Reading or Writing Unicode from a Filehandle
    22. 8.21. Converting Microsoft Text Files into Unicode
    23. 8.22. Comparing the Contents of Two Files
    24. 8.23. Pretending a String Is a File
    25. 8.24. Program: tailwtmp
    26. 8.25. Program: tctee
    27. 8.26. Program: laston
    28. 8.27. Program: Flat File Indexes
  12. 9. Directories
    1. Introduction
    2. 9.1. Getting and Setting Timestamps
    3. 9.2. Deleting a File
    4. 9.3. Copying or Moving a File
    5. 9.4. Recognizing Two Names for the Same File
    6. 9.5. Processing All Files in a Directory
    7. 9.6. Globbing, or Getting a List of Filenames Matching a Pattern
    8. 9.7. Processing All Files in a Directory Recursively
    9. 9.8. Removing a Directory and Its Contents
    10. 9.9. Renaming Files
    11. 9.10. Splitting a Filename into Its Component Parts
    12. 9.11. Working with Symbolic File Permissions Instead of Octal Values
    13. 9.12. Program: symirror
    14. 9.13. Program: lst
  13. 10. Subroutines
    1. Introduction
    2. 10.1. Accessing Subroutine Arguments
    3. 10.2. Making Variables Private to a Function
    4. 10.3. Creating Persistent Private Variables
    5. 10.4. Determining Current Function Name
    6. 10.5. Passing Arrays and Hashes by Reference
    7. 10.6. Detecting Return Context
    8. 10.7. Passing by Named Parameter
    9. 10.8. Skipping Selected Return Values
    10. 10.9. Returning More Than One Array or Hash
    11. 10.10. Returning Failure
    12. 10.11. Prototyping Functions
    13. 10.12. Handling Exceptions
    14. 10.13. Saving Global Values
    15. 10.14. Redefining a Function
    16. 10.15. Trapping Undefined Function Calls with AUTOLOAD
    17. 10.16. Nesting Subroutines
    18. 10.17. Writing a Switch Statement
    19. 10.18. Program: Sorting Your Mail
  14. 11. References and Records
    1. Introduction
    2. 11.1. Taking References to Arrays
    3. 11.2. Making Hashes of Arrays
    4. 11.3. Taking References to Hashes
    5. 11.4. Taking References to Functions
    6. 11.5. Taking References to Scalars
    7. 11.6. Creating Arrays of Scalar References
    8. 11.7. Using Closures Instead of Objects
    9. 11.8. Creating References to Methods
    10. 11.9. Constructing Records
    11. 11.10. Reading and Writing Hash Records to Text Files
    12. 11.11. Printing Data Structures
    13. 11.12. Copying Data Structures
    14. 11.13. Storing Data Structures to Disk
    15. 11.14. Transparently Persistent Data Structures
    16. 11.15. Coping with Circular Data Structures Using Weak References
    17. 11.16. Program: Outlines
    18. 11.17. Program: Binary Trees
  15. 12. Packages, Libraries, and Modules
    1. Introduction
    2. 12.1. Defining a Module’s Interface
    3. 12.2. Trapping Errors in require or use
    4. 12.3. Delaying use Until Runtime
    5. 12.4. Making Variables Private to a Module
    6. 12.5. Making Functions Private to a Module
    7. 12.6. Determining the Caller’s Package
    8. 12.7. Automating Module Cleanup
    9. 12.8. Keeping Your Own Module Directory
    10. 12.9. Preparing a Module for Distribution
    11. 12.10. Speeding Module Loading with SelfLoader
    12. 12.11. Speeding Up Module Loading with Autoloader
    13. 12.12. Overriding Built-in Functions
    14. 12.13. Overriding a Built-in Function in All Packages
    15. 12.14. Reporting Errors and Warnings Like Built-ins
    16. 12.15. Customizing Warnings
    17. 12.16. Referring to Packages Indirectly
    18. 12.17. Using h2ph to Translate C #include Files
    19. 12.18. Using h2xs to Make a Module with C Code
    20. 12.19. Writing Extensions in C with Inline::C
    21. 12.20. Documenting Your Module with Pod
    22. 12.21. Building and Installing a CPAN Module
    23. 12.22. Example: Module Template
    24. 12.23. Program: Finding Versions and Descriptions of Installed Modules
  16. 13. Classes, Objects, and Ties
    1. Introduction
    2. 13.1. Constructing an Object
    3. 13.2. Destroying an Object
    4. 13.3. Managing Instance Data
    5. 13.4. Managing Class Data
    6. 13.5. Using Classes as Structs
    7. 13.6. Cloning Constructors
    8. 13.7. Copy Constructors
    9. 13.8. Invoking Methods Indirectly
    10. 13.9. Determining Subclass Membership
    11. 13.10. Writing an Inheritable Class
    12. 13.11. Accessing Overridden Methods
    13. 13.12. Generating Attribute Methods Using AUTOLOAD
    14. 13.13. Coping with Circular Data Structures Using Objects
    15. 13.14. Overloading Operators
    16. 13.15. Creating Magic Variables with tie
  17. 14. Database Access
    1. Introduction
    2. 14.1. Making and Using a DBM File
    3. 14.2. Emptying a DBM File
    4. 14.3. Converting Between DBM Files
    5. 14.4. Merging DBM Files
    6. 14.5. Sorting Large DBM Files
    7. 14.6. Storing Complex Data in a DBM File
    8. 14.7. Persistent Data
    9. 14.8. Saving Query Results to Excel or CSV
    10. 14.9. Executing an SQL Command Using DBI
    11. 14.10. Escaping Quotes
    12. 14.11. Dealing with Database Errors
    13. 14.12. Repeating Queries Efficiently
    14. 14.13. Building Queries Programmatically
    15. 14.14. Finding the Number of Rows Returned by a Query
    16. 14.15. Using Transactions
    17. 14.16. Viewing Data One Page at a Time
    18. 14.17. Querying a CSV File with SQL
    19. 14.18. Using SQL Without a Database Server
    20. 14.19. Program: ggh—Grep Netscape Global History
  18. 15. Interactivity
    1. Introduction
    2. 15.1. Parsing Program Arguments
    3. 15.2. Testing Whether a Program Is Running Interactively
    4. 15.3. Clearing the Screen
    5. 15.4. Determining Terminal or Window Size
    6. 15.5. Changing Text Color
    7. 15.6. Reading Single Characters from the Keyboard
    8. 15.7. Ringing the Terminal Bell
    9. 15.8. Using POSIX termios
    10. 15.9. Checking for Waiting Input
    11. 15.10. Reading Passwords
    12. 15.11. Editing Input
    13. 15.12. Managing the Screen
    14. 15.13. Controlling Another Program with Expect
    15. 15.14. Creating Menus with Tk
    16. 15.15. Creating Dialog Boxes with Tk
    17. 15.16. Responding to Tk Resize Events
    18. 15.17. Removing the DOS Shell Window with Windows Perl/Tk
    19. 15.18. Graphing Data
    20. 15.19. Thumbnailing Images
    21. 15.20. Adding Text to an Image
    22. 15.21. Program: Small termcap Program
    23. 15.22. Program: tkshufflepod
    24. 15.23. Program: graphbox
  19. 16. Process Management and Communication
    1. Introduction
    2. 16.1. Gathering Output from a Program
    3. 16.2. Running Another Program
    4. 16.3. Replacing the Current Program with a Different One
    5. 16.4. Reading or Writing to Another Program
    6. 16.5. Filtering Your Own Output
    7. 16.6. Preprocessing Input
    8. 16.7. Reading STDERR from a Program
    9. 16.8. Controlling Input and Output of Another Program
    10. 16.9. Controlling the Input, Output, and Error of Another Program
    11. 16.10. Communicating Between Related Processes
    12. 16.11. Making a Process Look Like a File with Named Pipes
    13. 16.12. Sharing Variables in Different Processes
    14. 16.13. Listing Available Signals
    15. 16.14. Sending a Signal
    16. 16.15. Installing a Signal Handler
    17. 16.16. Temporarily Overriding a Signal Handler
    18. 16.17. Writing a Signal Handler
    19. 16.18. Catching Ctrl-C
    20. 16.19. Avoiding Zombie Processes
    21. 16.20. Blocking Signals
    22. 16.21. Timing Out an Operation
    23. 16.22. Turning Signals into Fatal Errors
    24. 16.23. Program: sigrand
  20. 17. Sockets
    1. Introduction
    2. 17.1. Writing a TCP Client
    3. 17.2. Writing a TCP Server
    4. 17.3. Communicating over TCP
    5. 17.4. Setting Up a UDP Client
    6. 17.5. Setting Up a UDP Server
    7. 17.6. Using Unix Domain Sockets
    8. 17.7. Identifying the Other End of a Socket
    9. 17.8. Finding Your Own Name and Address
    10. 17.9. Closing a Socket After Forking
    11. 17.10. Writing Bidirectional Clients
    12. 17.11. Forking Servers
    13. 17.12. Pre-Forking Servers
    14. 17.13. Non-Forking Servers
    15. 17.14. Multitasking Server with Threads
    16. 17.15. Writing a Multitasking Server with POE
    17. 17.16. Writing a Multihomed Server
    18. 17.17. Making a Daemon Server
    19. 17.18. Restarting a Server on Demand
    20. 17.19. Managing Multiple Streams of Input
    21. 17.20. Program: backsniff
    22. 17.21. Program: fwdport
  21. 18. Internet Services
    1. Introduction
    2. 18.1. Simple DNS Lookups
    3. 18.2. Being an FTP Client
    4. 18.3. Sending Mail
    5. 18.4. Reading and Posting Usenet News Messages
    6. 18.5. Reading Mail with POP3
    7. 18.6. Simulating Telnet from a Program
    8. 18.7. Pinging a Machine
    9. 18.8. Accessing an LDAP Server
    10. 18.9. Sending Attachments in Mail
    11. 18.10. Extracting Attachments from Mail
    12. 18.11. Writing an XML-RPC Server
    13. 18.12. Writing an XML-RPC Client
    14. 18.13. Writing a SOAP Server
    15. 18.14. Writing a SOAP Client
    16. 18.15. Program: rfrm
    17. 18.16. Program: expn and vrfy
  22. 19. CGI Programming
    1. Introduction
    2. 19.1. Writing a CGI Script
    3. 19.2. Redirecting Error Messages
    4. 19.3. Fixing a 500 Server Error
    5. 19.4. Writing a Safe CGI Program
    6. 19.5. Executing Commands Without Shell Escapes
    7. 19.6. Formatting Lists and Tables with HTML Shortcuts
    8. 19.7. Redirecting to a Different Location
    9. 19.8. Debugging the Raw HTTP Exchange
    10. 19.9. Managing Cookies
    11. 19.10. Creating Sticky Widgets
    12. 19.11. Writing a Multiscreen CGI Script
    13. 19.12. Saving a Form to a File or Mail Pipe
    14. 19.13. Program: chemiserie
  23. 20. Web Automation
    1. Introduction
    2. 20.1. Fetching a URL from a Perl Script
    3. 20.2. Automating Form Submission
    4. 20.3. Extracting URLs
    5. 20.4. Converting ASCII to HTML
    6. 20.5. Converting HTML to ASCII
    7. 20.6. Extracting or Removing HTML Tags
    8. 20.7. Finding Stale Links
    9. 20.8. Finding Fresh Links
    10. 20.9. Using Templates to Generate HTML
    11. 20.10. Mirroring Web Pages
    12. 20.11. Creating a Robot
    13. 20.12. Parsing a Web Server Log File
    14. 20.13. Processing Server Logs
    15. 20.14. Using Cookies
    16. 20.15. Fetching Password-Protected Pages
    17. 20.16. Fetching https:// Web Pages
    18. 20.17. Resuming an HTTP GET
    19. 20.18. Parsing HTML
    20. 20.19. Extracting Table Data
    21. 20.20. Program: htmlsub
    22. 20.21. Program: hrefsub
  24. 21. mod_perl
    1. Introduction
    2. 21.1. Authenticating
    3. 21.2. Setting Cookies
    4. 21.3. Accessing Cookie Values
    5. 21.4. Redirecting the Browser
    6. 21.5. Interrogating Headers
    7. 21.6. Accessing Form Parameters
    8. 21.7. Receiving Uploaded Files
    9. 21.8. Speeding Up Database Access
    10. 21.9. Customizing Apache’s Logging
    11. 21.10. Transparently Storing Information in URLs
    12. 21.11. Communicating Between mod_perl and PHP
    13. 21.12. Migrating from CGI to mod_perl
    14. 21.13. Sharing Information Between Handlers
    15. 21.14. Reloading Changed Modules
    16. 21.15. Benchmarking a mod_perl Application
    17. 21.16. Templating with HTML::Mason
    18. 21.17. Templating with Template Toolkit
  25. 22. XML
    1. Introduction
    2. 22.1. Parsing XML into Data Structures
    3. 22.2. Parsing XML into a DOM Tree
    4. 22.3. Parsing XML into SAX Events
    5. 22.4. Making Simple Changes to Elements or Text
    6. 22.5. Validating XML
    7. 22.6. Finding Elements and Text Within an XML Document
    8. 22.7. Processing XML Stylesheet Transformations
    9. 22.8. Processing Files Larger Than Available Memory
    10. 22.9. Reading and Writing RSS Files
    11. 22.10. Writing XML
  26. About the Authors
  27. Colophon
  28. Copyright