Wrox Professional Perl Programming Feb 2001 ISBN 1861004494 pdf
Professional Perl Programming
Peter Wainwright
with Aldo C alpini
Arthur Corliss Simon Cozens
Juan Julián M erelo Guervós C hris Nandor
Aalhad Saraf Wrox Press Ltd.
] TE AM
FL
Y®
Professional Perl Programming
© 2001 W rox Press All rights reserved. No part of this book m ay be reproduced, stored in a retrieval system or transm itted in any form or by any means, without the prior written perm ission of the publisher, except in the case of brief quotations em bodied in critical articles or reviews. The author and publisher have m ade every effort in the preparation of this book to ensure the accuracy of the inform ation. H owever, the inform ation contained in this book is sold without warranty, either express or im plied. Neither the authors, W rox Press nor its dealers or distributors will be held liable for any dam ages caused or alleged to be caused either directly or indirectly by this book.
Published by W rox Press Ltd, Arden H ouse, 1102 W arwick Road, Acocks G reen,
Birm ingham, B27 6BH , U K Printed in the United States
ISBN 1-861004-49-4
Trademark Acknowledgements
W rox has endeavored to provide trademark inform ation about all the com panies and products m entioned in this book by the appropriate use of capitals. H owever, W rox cannot guarantee the accuracy of this inform ation.
Credits Author Technical Reviewers
Peter W ainwright Simon Cozens C arl C ulvett
Contributing Authors
David Fannin Aldo C alpini Iain Georgeson Arthur Corliss Terry G liedt Simon Cozens Jim H arle Juan Julián M erelo Guervós C hris Lightfoot
M ark M am one C hris Nandor Aalhad Saraf Neil M atthews
Bill M oss
Technical Architect
Nathan Neulinger Louay Fatoohi Gavin Sm yth
Rick Stones
Technical Editors Paul W arren
M ankee C heng Andrew Yourtchenko David Mercer Philips Yuson Andrew Polshaw
Production M anager
Dan Robotham Simon H ardware
Additional Editorial Production Project Coordinator
M oham med Rfaquat M ark Burdett
Author Agents
Julia Gilbert Illustrations Velim ir Ilic Shabnam H ussain
Project Administrator Cover
Nicola Phillips Shelley Frazier
Indexers Proof Readers
Alessandro Ansa C hris Sm ith Adrian Axinte Keith W estmoreland Bill Johncocks Diana Skeldon
Category M anagers
Viv Em ery Paul C ooper
About the Authors
Peter Wainwright
Peter W ainwright is a freelance developer and software consultant. H e got his first taste of program m ing on a BBC Micro and gained m ost of his early program m ing experience writing applications in C on Solaris. H e then discovered Linux, shortly followed by Perl and Apache, and has been happily program m ing there ever since.
O utside of the software industry, he is a partner of Space Future Consulting, an international space tourism consultancy firm. H e spends much of his free tim e maintaining the non-profit Space Future website at www.spacefuture.com and writes the occasional article on space tourism. H e is also an advisor to the board of one or two com panies engaged in space tourism and vehicle development. If you have $50m to spare, he would like to have a word with you.
Professional Perl Programming
As well as being the primary author of , he is the author of
Professional Apache (ISBN: 1861003021)
, also published by W rox Press, as well as a contributing
Beginning Per l (ISBN: 1861003145)
author to . Formerly based in London, he recently moved from England to the Upper W est Side of N ew York to be with his new wife, a professional editor, whom he m et through a mutual interest in space tourism and low-rent apartm ents.
Aldo Calpini
Aldo C alpini is well known in the Perl com m unity for his m any im portant Win32 modules. H is active participation on several m ailing lists has helped the Perl language grow in the W in32 com munity. H e began programm ing twenty years ago and still enjoys hacking every kind of com puter he can put his hands on. H e works today as lead program mer in an Italian Internet startup company.
Arthur Corliss
Arthur Corliss has been program m ing since buying his first hom e computer a Timex Sinclair 1000 with a whopping 2K of RAM (which he still has). H aving worked his way through several languages, Perl has become his most frequent language of choice at his latest venture, Gallant Technologies, Inc., a software development com pany. O n his own tim e he continues the m adness by working on the Curses::Widgets and Curses::Forms modules, which he authored and is available on CPAN.
Simon Cozens
Simon Cozens is an O pen Source programm er and author; he writes for the Perl Journal, www.perl.com , and other sites, and is the author of W rox Press' Beginning Perl (ISBN:
1861003145) . H e is a mem ber of the Perl development team , and his hobbies include reading, typography and the Greek language and culture.
Juan Julián M erelo Guervós
Juan Julián Merelo Guervós was born in Ubeda, Jaén, Spain, the 10th of March of 1965. Juan received a degree in Theoretical Physics by the University of Granada in 1989, and a PhD in Physics in 1994. H e has been hacking PERL since 1993 or 1994, and is the author of a widely popular (and pioneer) web tutorial of PERL in Spanish (available from http://www.granavenida.com/perl
). Currently Juan is an associate professor at Granada U niversity, in Spain. H e is married and has three wonderful daughters, two of whom are fraternal twins, born in 1998 and 1999. H e can be reached at jmerelo@geneura.ugr.es , and his homepage (which is, so far, in Spanish) is at http://geneura.ugr.es/~jmerelo
Chris Nandor C hris N andor, pudge@pobox.com , is a programm er for O SD N , working on theSlashdot code.
MacPerl: Power and Ease (ISBN : 1881957322)
H e co-authored the book from Prim e Tim e Freeware, writes the Perl News column for the Perl Journal, and runs the web sites http://use.perl.org/ and http://news.perl.org/
. C hris lives in Massachusetts with his three dogs, two cats, and one wonderful and supportive wife, Jennifer.
I'd like to dedicate this book to my wife, my parents, and my in-laws who've all given me encouragement & put up with me during deadlines.
Aalhad Saraf Aalhad Saraf is in the System s Software G roup in IBM Labs. H e has been with Linux since 1995
Perl, C , and C+ + are his favorite tools. H as a Bachelors degree in Electronics Engineering from the U niversity of Pune, a Post G raduate D iplom a awarded by the national resource center of the 'C enter for D evelopm ent of Advanced Com puting' (a scientific society of the Ministry of IT, G ovt. of India). H e worked on m icrocontrollers/ embedded system s and hand-held com puting devices in Syslab Autom ation and on an interactive gam ing server for D ishnetDSL – one of India's leading ISPs. H e also teaches Perl, Software Engineering and Q uality systems during his spare time. H e Takes his table tennis seriously, fiddles around with a guitar, juggles tennis balls and is an om nivore when it comes to reading. H e likes networks. H e dream s of traveling through space sitting in a packet; playing with the civilization of Data, providing the subjects – bytes, with new worlds and increasingly better m eans of transport. Aalhad is 22 years old and aspires to get a Ph.D. in C om puter Science some day.
Table of Contents
Introduction 1
18 Installing Modules with the 'CPAN' Module
32 General Environment Variables Used by Perl 32 Perl Specific Environment Variables 32 Summary
30 Supplying Arguments to Perl Scripts 30 Using Perl as a Generic Command Line Utility 31 The Perl Environment
29 Command Line Syntax
27 Perl on UNIX 28 Perl on Windows 28 Perl on Macintosh 29 The Command Line
27 Starting Perl Applications
18 Starting and Configuring CPAN 19 Installing Modules 20 Listing and Searching CPAN 21 Reading Module Documentation Without Installing 23 Reloading CPAN 23 Configuring CPAN Options 24 Installing Modules by Hand 24 Running Perl
14 Building a Threaded Perl Interpreter 17 Differences for Windows and Macintosh 17 Other Platforms 17 Building and Installing Modules
7 Key Features
12 Installing Perl on UNIX 13 Installing Perl on Windows 13 Installing Perl on Macintosh 14 Building Perl from Source
12 Installing Pre-built Perl Distributions
10 Building and Installing Perl
10 Essential Information
9 Perl History and Versions
8 Supported Platforms
33 Table of Contents ii
35 Whitespace
52 Integers
80 Summary
71 Print 71 Line Terminator Termination 72 Characters and Character Codes 73 Length and Position 73 Substrings and Vectors 74 Upper and Lower Case 75 Interpolation 75 Pattern Matching and Transliteration 75 Password Encryption 76 Low Level String Conversions 76 String Formatting
69 Functions For Manipulating Strings
68 Converting Strings into Lists and Hashes
67 Converting Strings into Numbers
65 Bareword Strings and Version Numbers
62 'Here' Documents
62 Quotes and Quoting
61 Strings
60 Mathematical Functions
56 Converting Floats into Integers 58 Converting Floats into Strings 58 The 'use integer' Pragma
53 Integer Range and Big Integers 53 Converting Integers into Floating-Point Numbers 54 Converting Integers into Strings 54 Handling Different Number Bases 55 Floating-Point Numbers
51 Numbers
36 Data Types
47 Chapter 3: Scalars 51 Value Conversion and Caching
47 Scoping
46 Functions
45 Subroutines
43 Loop Modifiers
43 Control Constructs
42 Blocks
42 Operators
41 Void Context
40 Scalar and List Context
39 Context
39 Interpolation
36 Special Variables
84 Table of Contents
Chapter 4: Operators 87
Operators Versus Functions87 Operator Types and Categories
88 Assignment
89 Arithmetic
89 Shift
91 String and List
91 Logical
93 Bitwise
94 Combination Assignment
97 Increment and Decrement
98 Comparison
99 Regular Expression Binding 101 Comma and Relationship 101 Reference and Dereference 102 The Arrow 102 Range 103 Ternary 105
Precedence and Associativity 106
Precedence and Parentheses 107
Disabling Functions and Operators 110
Overriding Operators 113
Summary 114
Chapter 5: Beyond Scalars – More Data Types 117
Lists and Arrays117
Manipulating Arrays Adding Elements to an Array Removing Elements from an Array Counting an Array Removing All Elements from an Array Modifying the Contents of an Array Resizing and Truncating an Array 119 123 125 119 123 121 122 Changing the Starting Index Value Sorting and Reversing Lists and Arrays 127 125
Converting Lists and Arrays into Scalars Taking References Converting Lists into Formatted Strings 127 127 127
Hashes 129
Manipulating Hashes Removing Hash Keys and Values Adding and Modifying Hash Values 131 132 131 Converting Lists and Arrays into Hashes Accessing and Iterating Over Hashes Reversing Hashes
132 134 133 Converting Hashes into Scalars 137 Converting Hashes into Arrays 138 The Special Hash '%ENV' 'Env.pm' Handling Tainted Input from '%ENV' Configuring Programs via '%ENV'
138 141 140 140 iii Table of Contents iv
References 142
Constants 169
Conditional Statements 183
The 'do' Block 181 Special Blocks 182
Declarations 176 Expressions and Simple Statements 176 Blocks and Compound Statements 177 Blocks in Perl Statements 178 Naked Blocks 178 Defining the Main Program as a Block 179 Blocks as Loops 180
175
Summary 172
Declaring Scalar Constants with the 'constant' Pragma 169 Declaring List and Hash Constants 171 Constant References 171 Listing and Checking for the Existence of Constants 172
Tests of Existence 166 Using the Undefined Value 167 Using 'undef' as a Function 168
Hard References 142 Creating References 143 Comparing References 144 Dereferencing 145 Working with References 146 Passing References to Subroutines 147
The Undefined Value 164
Defining Typeglobs 161 Manipulating Typeglobs 162 Accessing Typeglobs 163
Typeglobs 161
The Problem with Nesting – My Lists Went Flat! 151 Lists of Lists and Multidimensional Arrays 151 Hashes of Hashes and Other Animals 153 Adding to and Modifying Complex Data Structures 154 Creating Complex Data Structures Programmatically 155 Traversing Complex Data Structures 158
Complex Data Structures 151
Finding the Type of a Reference 148
What Is Truth? 184 'if', 'else', and 'elsif' 185 'unless' 187 Writing Conditions with Logical Operators 188 The Ternary Operator 189 Switches and Multi-Branched Conditions 192 Returning Values from Multi-Branched Conditions 194
Table of Contents v
Passing Parameters 228
248 Assignable Subroutines 250
Returning the Undefined Value 244 Determining and Responding to the Calling Context 246 Handling Void Context 247 Handling Context: an Example 247 Closures
Returning Values from Subroutines 243
Defining the Number of Parameters and Their Scope 237 Prototyping Code References 239 Subroutines as Scalar Operators 239 Requiring Variables Rather than Values 240 Optional Parameters 241 Disabling Prototypes 242
Prototypes 236
Passing Lists and Hashes 229 Converting Scalar Subroutines into List Processors 231 Passing '@_' Directly into Subroutines 232 Named Parameters 233
221 Recursion 223 Checking for Subroutines and Defining Subroutines On the Fly 226
Loops and Looping 195
Anonymous Subroutines and Subroutine References 217 Strict Subroutines and the 'use strict subs' Pragma 219 Predeclaring Subroutines 219 Overriding Built-in Functions 220 The Subroutine Stack
216
Summary 213
209 'maps' and 'greps' 210 'map' 211 'grep' 211
Controlling Loop Execution 204 The 'continue' Clause 206 Controlling Nested Loops 207 The Trouble with 'do' 208 The 'goto' Statement
200 Variable Aliasing with 'while' 201 Looping over Lists and Arrays with 'while' 201 Looping on Self-Modifying Arrays 202 Looping over Hashes with 'while' 203 'do...while' and 'do...until' 203
Writing C-style Loops with 'for' 195 Writing Better Loops with 'foreach' 197 Using 'foreach' with Multi-Branched Conditions 198 Variable Aliasing in 'foreach' Loops 199 Conditional Loops – 'while', 'until', and 'do'
TE
AM FL Y ® Table of Contents vi
Attribute Lists 251
277
Postponing Module Loading Until Use 290
Finding Out What Modules are Installed 286
Checking for the Availability of a Module 286
Locating Libraries Relative to the Script 285
Modifying '@INC' directly 283 Modifying @INC with the 'lib' Pragma 284
The Special Array '@INC' 283
The Special Hash '%INC' 282
How Pragmatic Modules Work 280 Scope of Pragmatic Modules 281
Pragmatic Modules 280
'import' Lists 278 Suppressing Default Imports 279 Disabling Features with 'no' 279 Testing for Module Versions and the Version of Perl 279
276 Loading Code Using 'do', 'require', and 'use'
Defining Attributes on Subroutines 251 Accessing Attributes 252 Special Attributes 252 Package Attributes 253
Chapter 9: Using Modules 275
Modules and PackagesSummary 273
The 'main' Package 267 Typeglobs and the 'main' Package 268 The Symbol Table Hierarchy 269 Manipulating the Symbol Table Directly 270 Accessing the Symbol Table 271
The Symbol Table 267
Declaring Lexical Variables 265 Preserving Lexical Variables Outside Their Scope 266
Lexical Variables 264
Defining Package Variables 258 Using 'strict' Variables 259 Declaring Global Package Variables 260 Declaring Global Package Variables with 'use vars' 260 Lexically Declaring Global Package Variables with 'our' 261 Automatic Localization in Perl 262 Localizing Package Variables with 'local' 262
257
Chapter 8: Scope and Visibility 257
Package VariablesSummary 254
Summary 292
Table of Contents vii
The 'import' Mechanism 316 Exporting 319 Setting Flags with Exports 321 When to Export, When not to Export 321 The 'Exporter' Module 322
Regular Expressions 345
340 Interpolating Code 341 Interpolative Context 342 Interpolation in Regular Expressions 342 Interpolating Text Inside String Variables 343 Protecting Strings Against Interpolation 344
Perl's Interpolation Syntax 337 Interpolating Metacharacters and Character Codes 338 Common Special Characters 339 Special Effects 339 Interpolating Variables
337
Chapter 11: Regular Expressions 337
String InterpolationSummary 335
Well-Written Modules 330 Creating a Working Directory 331 Building an Installable Package 332 Adding a Test Script 334 Uploading Modules to CPAN 334
Creating Installable Modules 330
Importing and Exporting 316
Chapter 10: Inside Modules and Packages 295
309 Autoloading Modules 310 Using the 'AutoLoader' Module 311 Using the 'SelfLoader' Module 314
Autoloading Subroutines 305 Using an 'AUTOLOAD' Subroutine as a Substitute 305 Defining Subroutines On the Fly 308 Self-Defining Instead of Autoloading Subroutines
Autoloading 304
Finding a Package Name Programmatically 303
Removing a Package 302 Forbidding Package Variables 303
Manipulating Packages 300
'BEGIN' Blocks 297 'END' Blocks 299 'CHECK' and 'INIT' 299
'BEGIN' blocks, 'END' blocks and Other Animals 296
Where Regular Expressions Occur 346 Matching and Substitution 346 The 'split' Function 347 Pre-compiled Regular Expressions 348 Table of Contents viii
Regular Expression Delimiters 349 Elements of Regular Expressions 350 More Advanced Patterns 352 Matching Arbitrary Characters and Character Classes 352 Repetition and Grouping 354 Matching Sequential and Overlapping Terms 361 Pattern Match Modifiers
362 Regular Expressions versus Wildcards 363 Metacharacters 365 Character Class Metacharacters 365 Zero-Width Metacharacters 368 Extracting Matched Text
369 Special Variables 369 Parentheses and Numbered Variables 371 Backreferences 374 Extracting Lines with the Range Operator 376 Matching More than Once 378 Regular Expressions and Loops 378 Nested Regular Expression Loops 380 Position 382 Matching In and Across Multiple Lines 384 Counting the Total Number of Matches 386
Overlapping Matches and Zero-Width Patterns 386 Extended Patterns
389 Documenting Regular Expressions 389 Writing Efficient Regular Expressions 391 Making Regular Expressions More Specific 391 'study' 393 Avoiding Recompilation with the Empty Pattern 394 Avoiding Recompilation with the 'once-only' Modifier 394
Generating Regular Expressions with 'eval' 395 Predefining Search Patterns with 'qr' 397 Checking the Validity of Regular Expressions
399 Regular Expressions, Tainted Variables, and Debugging 401 Untainting Tainted Variables 401 Maintaining Taintedness in Regular Expressions 401 Understanding and Debugging the Regular Expression Engine 402 Substitution 407 Substituting Matched Text and Interpolation 407 Evaluating the Replacement String 408 Interpolating and Evaluating the Replacement String 409 Transliteration
409 Transliteration Modifiers 411
Summary 412
416 The Filehandle Data Type
416 Standard Filehandles
416 Table of Contents ix
Creating Filehandles 417
'seek' to a Specific Place within a File 434 Clearing the End-of-File Condition with 'seek' 435 Writing at the End-of-File 436 Finding the Current Position 437 Object-Oriented Random Access 437
Caching Many Filehandles 446
Redirecting Filehandles 445
Duplicating and Aliasing Filehandles 444
Using Special Variables to Configure Other Filehandles 443 Automatically Restoring the Default Filehandle 443 Using Default Variables vs, 'IO::Handle' Methods 444
Changing the Default Output Filehandle 442
Establishing File Locks 440 File Locking Issues and Caveats 442
File Locking 439
Truncating and Resizing Files 437
Random Access 434
Creating Filehandles with 'open' 417 Opening Files for Reading, Writing, and Updating 418 Opening Arbitrary Filenames 419 Opening Standard Input and Standard Output 419 Creating Filehandles with 'IO::File' 420 The Data Filehandle 422 Other Filehandles 423
The 'binmode' Function 433 The 'open' Pragma 434
Handling Binary and Text Files 433
Buffering and Autoflush Mode 432 Alternatives to 'print' 432
Writing to Filehandles 430
428 Detecting the End-of-File 429 Reading a Single Character 430
The Readline Operator 426 Redefining the Line Separator 426 Aliasing Readline in 'while' Loops 427 Counting Line Numbers 427 Readline and the '@ARGV' Array 428 Finer Control Over Reading
Reading from Filehandles 426
Referring to Filehandles 424
'IO::Handle' Methods and Special Variables 448 Table of Contents x
System Level IO 452
Opening Filehandles at the System Level 453 Open Mode Flags 453 Non-blocking IO 454 The Permissions Mask 455 Using 'sysopen' via 'IO::File' 456 Unbuffered Reading
456 Unbuffered Writing 457 System-Level File Positioning 458 'fcntl' and 'ioctl' 459 Setting Filehandle Attributes with 'fcntl' 459 Controlling Devices with 'ioctl' 462 POSIX IO
462 POSIX Filehandle Routines 463 POSIX File Descriptor Routines 463 Moving between POSIX and Standard IO 464
Summary 465
467
Getting User and Group Information 468 User Information 468 Group Information 473 The Unary File Test Operators
475 Link Transparency and Testing for Links 477 Testing Binary and Text Files 477 Reusing the Results of a Prior 'stat' or 'lstat' 478 Using 'stat' Objects 479 Access Control Lists, the Superuser, and the 'filestat' Pragma 480 Automating Multiple File Tests 482
Interrogating Files 484 Changing File Attributes 485 File Ownership 485 File Permissions 487 The 'Fcntl' Module
488 Linking, Unlinking, and Renaming Files 490 Linking Files 491 Unlinking Files 491 Renaming Files 492 Symbolic Links 492 Copying and Moving Files
493 System Level Copies and Platform Portability 495 Comparing Files 496 Finding Files 497 Deciphering File Paths 501 Filename Globbing 503 'glob' Syntax 504 UNIX Style File Globbing 505 DOS-Style File Globbing 507 Temporary Files
508 Creating a Temporary Filehandle 508 Temporary Filenames via the POSIX module 509 Using 'File::Temp' 511 Table of Contents xi
Manipulating Directories 513
Reading Directories 513 Directory Positions 514 Directory Handle Objects 515 Directories as Tied Hashes 515 Finding the Name of a Directory or File from its Handle 516 Creating and Destroying Directories
517 Creating Single Directories 517 Creating Multiple Directories 518 Destroying Single Directories 519 Destroying Multiple Directories 520 Moving Around Directories 520
Summary 523
525
Command-Line Conventions 526 The '@ARGV' Array 527 Passing Arguments to Perl Itself 528 Setting Variables from '@ARGV' 528 Reading Files from '@ARGV' 529 '@ARGV' and Standard Input 531 Simple Command-Line Processing with 'Getopt::Std'
532 Basic Processing with 'getopt' 532 Slightly Smarter Processing with 'getopts' 534 More Complex Command-line Processing with 'Getopt::Long' 535 Simple Argument Processing 535 Option Prefixes 537 Defining Option Values 538 Abbreviations 541 Aliases 541 Handling Option Values 542 Documenting Options 544 Bundling Options 544 Case Sensitivity 546 Handling Unrecognized Option and Value Arguments 547 'POSIX' Mode 549 Summary of Configuration Options 549
Shells, Shell Commands, and Perl 551
Creating a Simple Perl Shell 551 Writing a More Useful Shell 552 Integrating the Shell into Perl 555 Emulating UNIX Commands on Windows 557
Summary 559 Table of Contents xii
Chapter 15: Terminal Input and Output 561
Talking to Terminals'Term::Screen' 588 The Curses Library 590 A Simple Curses Application 591 Curses Windows 593 Third-Party Extensions to Curses 594
604
603 Deciphering Error Results from System Calls
602 Intercepting Warnings and Errors
600 Generating Warnings and Errors
599 Enabling Diagnostics
Chapter 16: Warnings and Errors 599
Enabling Warnings597
Programming the Terminal Directly via 'POSIX' 594 Summary
Higher-Level Terminal Modules 588
561
584
Terminal Capabilities 581 Creating a Termcap Object 582 Clearing the Screen, Moving the Cursor, and Other Tricks 584 Writing in Colors
Writing to the Screen 581
580
568 Passwords and Invisible Input 569 Finding and Setting the Screen Size 569 Serial Connections and Terminal Speed 571 Line Ending Translation 571 Getting and Setting Control Characters 572 Advanced Line Input with 'Term::ReadLine' 574 Creating a Terminal Object 575 Supported Features 577 Setting the Prompt Style and Supplying Default Input 578 Command-Line History 579 Word Completion
Simple Input 563 Controlling Terminal Input with 'Term::ReadKey' 564 Read Modes 564 Reading a Single Character 566 Reading Complete Lines
Reading from the Keyboard 563
Determining if a Script is Interactive 562
Error Numbers and Names 604 Setting the Error Number 605 Errors from Evaluated Code 605 Extended Error Messages 606 'Errno' and The 'POSIX' Module 607 Checking the Exit Status of Subprocesses and External Commands 607
Table of Contents xiii
626 Configuring the Debugger 636 Interactively 636 Through the Environment 636 The '.perldb' Script 637 Debugger Configuration Options 638 Tracing and Terminals
Profiling Perl Applications 657 Generating Profile Reports 657 Collecting Timing Information Directly 661 Testing for Performance 663 'timeit' 665 'timethis' 666 'timethese' 667 'cmpthese' 667 'countit' 668
Profiling 656
Writing a Test Script 653 Automating Tests 655
Automated Testing 653
Debugging the Perl Interpreter 652
The 'Dumpvalue' Module 645 The 'Safe' Module 649 Creating Compartments 649 Sharing Variables and Subroutines 649 Operator Masks 650 The 'Safe' Module in Use 651
Debugging and Informational Modules 645
641 Entering the Debugger Programmatically 642 Using Debugger Hooks 643
Starting the Debugger 622 Entering Commands 623 Simple Debugging Commands – Single Stepping 624 Running Arbitrary Code 625 Multiline Commands 625 Debugging Commands
Making Non-Fatal Errors Fatal 608
The Perl Debugger 622
A Simple Debugging System 619 A Better Debugging System 619 Creating Debug Logs 621 Adding Calling Context to Debug Messages 621
618
617 Applications that Debug Themselves
615
612 Summary
611 Advanced Warnings
Returning Warnings and Errors in Context with 'Carp' 609 Error Logs and System Logs
Summary 669 Table of Contents xiv
672
Expanding and Contracting Tabs with 'Text::Tabs' 672 Calculating Abbreviations with 'Text::Abbrev' 673 Parsing Words and Phrases with 'Text::ParseWords' 675 Parsing Space-Separated Text 676 Parsing Arbitrarily Delimited Text 677 Batch Parsing Multiple Lines 678 Parsing a Single Line Only 679 Formatting Paragraphs with 'Text::Wrap'
679 Formatting Single Paragraphs 679 Customized Wrapping 680 Formatting Whole Documents 681 Formatting on the Command Line 681 Matching Similar Sounding Words with 'Text::Soundex' 682 Tokenizing Single Words 682 Tokenizing Lists of Words and E-Mail Addresses 683 The 'Soundex' Algorithm 684 Handling Untokenizable Words 684 Other Text Processing Modules
684
Documenting Perl 684
Comments 685 plain old documentation 685 pod Paragraphs 685 Using pod with 'DATA' or 'END' tokens 690 Interior Sequences 691 Pod Tools and Utilities
691 Translator Tools 691 Retrieval Tools 692 pod Verification 692 Programming pod 694 Using Pod Parsers 695 Writing a pod Parser 695 Locating pods 698
Reports – The 'r' in Perl 699
Formats and the Format Datatype 699 Formats and Filehandles 701 Assigning Formats to Standard Output 702 Determining and Assigning Formats to Other Filehandles 703 Format Structure
704 Picture Lines and Placeholders 704 Data Lines 707 Suppressing Redundant Lines 708 Autorepeating Pattern Lines 709 Page Control 709 Creating Footers 711 Combining Reports and Regular Output
712 Mixing 'write' and 'print' 712 Generating Report Text with 'formline' 714
Summary 715
Table of Contents xv
Inheritance and Subclassing 753
Private Class Data 778 Private Object Data 778
Keeping Data Private 777
Autoloading Methods 773
764 Writing Classes for Multiple Inheritance 765 Drawbacks with Multiple Inheritance 767 A 'UNIVERSAL' Constuctor 768 Is-a Versus Has-a 770
756 More on Class Data through Objects 756 Exports 759 Private Methods 760 Extending and Redefining Objects 761 Extending a Parent Class 761 Constructing Subclasses On the Fly 762 Multiple Inheritance
Inheriting from a Parent Class 754 Overriding and Calling Overridden Methods 754 Overriding and Calling Overridden Constructors 755 Writing Inheritable Classes
747
718
Constructors 727 Choosing a Different Underlying Data Type 729 Methods 732 Object Data 736 Class Data 740 Debugging Object Classes
Writing Object Classes 727
724 Determining Inherited Characteristics 725 Determining an Object's Ancestry 725 Determining an Object's Capabilities 725 Determining an Object's Version 726
Creating Objects 721 Using Objects 722 Accessing Properties 722 Calling Class Methods 723 Calling Object Methods 724 Nesting Method Calls 724 Determining what an Object Is
Programming with Objects 721
Polymorphism 720 Overloading 720 Adaptabilty (also called Casting or Conversion) 721
Object Concepts 718 Classes 718 Objects 718 Inheritance, Multiple Inheritance, and Abstraction 719 Public and Private Methods and Data 720
TE
AM FL Y ® Table of Contents xvi
Destroying Objects 782
815
PVs 828
Internal Variable Types 827
Parsing 822 Compiling 824 Interpreting 826
How Perl Works 822
Around the Source Tree 818 Building Perl 821 'metaconfig' Rather than 'autoconf'? 821
Under the Hood 818
'perl -V' 816 How It Works 817 Platform 817 Compiler 817 Linker and Libraries 818 Dynamic Linking 818
Summary 811
Destructors and Inheritance 783 Destructors and Multiple Inheritance 784
802 Standard Tie Object Classes 803 Tied Object Methods 803 An Example Tied Hash Class 807 An Example Class Using 'Tie::StdHash' 809
Using Tied Objects 800 Handling Errors from 'tie' 800 Accessing Nested References 801 Testing a Variable for 'tied'ness 801 'Untie'ing Objects 802 Writing Tied Objects
Ties and Tied Objects 799
Automating Object Class Development 795
791 Overloading and Inheritance 793 Autogenerated Operations 793 Overloadable Operations 795
Basic Overloading 785 Determining the Operand Order and Operator Name 786 Overloading Comparisons 787 Overloading Conversion Operations 788 Overloading String Conversion 788 Overloading Numeric Conversion 790 Falling Back to Unoverloaded Operations
Overloading Operators 785
IVs 828 NVs 829 Arrays and Hashes 830 Examining Raw Datatypes with 'Devel::Peek' 830
Table of Contents xvii
XS Functions 862 Putting the 'CODE' in 862 Complex Output, 'PPCODE' and the Stack 863 Complex Input, Default Values and Variable Input Lists 865 The 'TYPEMAP'
877 Embedding Perl Code 880 Getting Perl Values 881 Using Perl Subroutines 882 Working with Perl Internals 884 Using Modules 886
First Steps 875 Building a Program (The Hard Way) 876 Building a Program (The Easy Way) 877 Implementing the Perl Interpreter
Using Perl from C 875
Using the 'FFI' Module 872 Using the 'C::DynaLib' Module 874 Using the 'Win32::API' module 875
Dynamic Linking 871
867 The 'Makefile' 870
860 Declaring the 'MODULE' and 'PACKAGE' 861
The Perl Compiler 833
An Overview of XS 857 'h2xs', or Where to Start 857 Converting C Header Files 858 Starting from Scratch 860 The XS File
856
Summary 853
850
'B::Bytecode' 842 'B::Disassembler' 843 'B::Lint' 843 'B::Showlex' 845 'B::Xref' 845 'B::Fathom' 848 'B::Graph' 848 'B::JVM::Jasmin' 849 Writing a Perl Compiler Backend
The 'O' Module 834 The 'B' Module 834 The 'B::' Family of Modules 836 'B::Terse' 836 'B::Debug' 837 'B::Deparse' 839 'B::C' 840 'B::CC' 841
The Java-Perl Lingo 888 Table of Contents xviii
Perl and COM 889
Waiting for an Only Child 912 Getting the Exit Status 912 Handling Multiple Child Processes 913 POSIX Flags and Functions 914
953
Checking for Thread Support 938 Creating Threads 938 Identifying Threads 939 Thread-specific Data 940 Thread Management 940 Variable Locks 942 Condition Variables, Semaphores, and Queues 943 Condition Variables 943 Semaphores 947 Queues 950 Thread Safety and Locked Code
Threads 937
IPC::SysV 927 Messages Queues 928 Semaphores 931 Shared Memory Segments 935
Sharing Data Between Processes 926
Very Simple Solutions 916 Pipes 917 Opening and Running External Processes 919 Bi-directional Pipes 920 Avoiding Shells with the Forked Open 922 Bi-directional Pipes to External Processes 923 Handling Bi-directional Communications 925
Communicating Between Processes 916
Handling Children and Returning Exit Codes 911
PerlCOM 889 'PerlCtrl' 890
Replacing the Current Process with Another 909 Process IDs 909 Process, Groups and Daemons 909
Starting New Processes 908
905 Alarms 906 A Simple Use of Alarms 906 Using Alarms to Abort Hung Operations 907
Signal Handling 898 The 'die' and 'warn' Handlers 900 Writing Signal Handlers 900 Avoid Complex Handlers 901 Flexibly Installing Signal Handlers 903 Sending Signals
895
Summary 893
The Filter Module 892
Miscellaneous Languages 891
Summary 954
Table of Contents xix
1012
External Subroutines (XS) 1025
Inter-Process Communication (IPC) 1025
System Interaction 1024
Endianness and Number Width 1023
Portable File Handling with 'File::Spec' 1020
1018
1016 Files and File Systems
1016 Newlines
Chapter 24: Writing Portable Perl 1015
Maybe We Shouldn't Bother?Summary 1013
System Network Files 1001 Hosts 1003 Networks 1007 Network Services 1009 Network Protocols 1011 Determining the Local Hostname
Chapter 23: Networking with Perl 957
An Introduction to NetworksGetting Network Information 1000
A Simple Threaded Server 999
Polling Servers 993 The 'select' Function 993 The' IO::Select' Module 995 A Simple Polling Server 996 A Simple Forking Server 998
Multiplexed Servers 992
UNIX Sockets 989
Sockets 967 'Socket.pm' 967 'IO::Socket.pm' 976 TCP INET Examples 979 UDP INET Examples 986
Networking with Perl 967
ICMP 965 Other Protocols 966 Presentation/Application Layers 966 Anonymous, Broadcast, and Loopback Addresses 966
960 UDP & TCP 964
Protocol Layers 957 Frames, Packets, and Encapsulation 959 The Internet Protocol
957
Modules 1026 Table of Contents xx
Time and Date 1026
1044 Data in Perl
Work in Progress 1059
Installing Unicode Fonts 1055 Installing a Unicode Editor 1055 Creating the HTML Template 1056 Processing the Resource Files 1057 Running the Script 1058 The Output Files 1058
Perl, I18n and Unicode 1055