Lee Perl Companion eBook Available Beginning James Lee, Author of Hacking Linux Exposed this print for content only—size & color not accurate CYAN MAGENTA YELLOW BLACK PANTONE 123 C BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® Beginning Perl Dear Reader, Whether you are a complete novice or an experienced programmer, you hold in your hands the ideal guide to learning Perl. Originally created as a powerful text processing tool, Perl has since evolved into a multipurpose, multiplatform programming language capable of implementing a variety of tasks such as system administration, web and network programming, and XML processing. In this book I will provide valuable insight into Perl's role regarding several of these tasks and more. Starting with a comprehensive overview of the basics of Perl, I'll introduce important concepts such as Perl's data types and control flow constructs. This material sets the stage for a discussion of more complex topics, such as writing custom functions, using regular expressions, and file input and output. Next, we move on to the advanced topics of object-oriented programming, modules, CGI programming, and database administration with Perl's powerful database interface module, DBI. The examples and code provided offer you all of the information you need to start writing your own powerful scripts to solve the problems listed above, and many more. After years of experience programming in this powerful language, I've come to appreciate Perl's versatility and functionality for solving simple and highly complex problems alike. Plus, Perl is one of the most enjoyable languages to use—programming in Perl is fun! I am confident that once you have studied the material covered in this book, you'll feel the same. James Lee US $39.99 Shelve in: Perl User level: Beginning www.apress.com SOURCE CODE ONLINE Companion eBook See last page for details on $10 eBook version ISBN 978-1-4302-2793-9 9 781430 227939 5 39 9 9 THE APRESS ROADMAP The Definitive Guide to Catalyst Pro Perl Linux System Administration Recipes Beginning Perl 3rd Ed Beginning Portable Shell Scripting Covers Perl 5.10 THIRD EDITION 7.5 x 9.25 spine = 0.875" 464 page count THE EXPERT’S VOICE ® IN OPEN SOURCE Perl THIRD EDITION James Lee Perl for those who missed it the first time around: Learn about the duct tape for the web, the cloud and system administration Beginning Covers Perl 5.10 Beginning Perl Third Edition ■ ■ ■ JAMES LEE with SIMON COZENS www.wowebook.com ii Beginning Perl, Third Edtion Copyright © 2010 by James Lee All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-2793-9 ISBN-13 (electronic): 978-1-4302-2794-6 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editor: Frank Pohlmann Technical Reviewers: Richard Dice, Ed Schaefer, Todd Shandelman Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Laurin Becker Copy Editors: Katie Stence, Sharon Terdeman Compositor: Kimberly Burton Indexer: Brenda Miller Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer- sbm.com, or visit www.springeronline.com. For information on translations, please e-mail rights@apress.com, or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is available to readers at www.apress.com. You will need to answer questions pertaining to this book in order to successfully download the code. iii For Polly and Dave Pistole i v Contents at a Glance ■About the Author xvi ■About the Technical Reviewers xvii ■Acknowledgements xviii ■Introduction xix ■Chapter 1: First Steps in Perl 1 ■Chapter 2: Scalars 13 ■Chapter 3: Control Flow Constructs 53 ■Chapter 4: Lists and Arrays 81 ■Chapter 5: Hashes 115 ■Chapter 6: Subroutines/Functions 131 ■Chapter 7: Regular Expressions 153 ■Chapter 8: Files and Data 179 ■Chapter 9: String Processing 207 ■Chapter 10: Interfacing to the Operating System 215 ■Chapter 11: References 231 ■Chapter 12: Modules 257 ■Chapter 13: Object-Oriented Perl 287 ■Chapter 14: Introduction to CGI 317 ■Chapter 15: Perl and DBI 349 ■Appendix: Exercise Solutions 387 ■Index 409 v Contents ■About the Author xvi ■About the Technical Reviewers xvii ■Acknowledgements xviii ■Introduction xix ■Chapter 1: First Steps in Perl 1 Programming Languages 1 Our First Perl Program 2 Program Structure 6 Character Sets 8 Escape Sequences 8 Whitespace 9 Number Systems 9 The Perl Debugger 11 Summary 11 Exercises 12 ■Chapter 2: Scalars 13 Types of Data 13 Numbers 14 Strings 17 Here-Documents 20 Converting Between Numbers and Strings 21 ■ CONTENTS CONTENTS vi Operators 22 Numeric Operators 22 String Operators 32 Operators to Be Covered Later 36 Operator Precedence 37 Variables 38 Scoping 43 Variable Names 46 Variable Interpolation 46 Currency Converter 48 Two Miscellaneous Functions 50 The exit() Function 50 The die() Function 51 Summary 52 Exercises 52 ■Chapter 3: Control Flow Constructs 53 The if Statement 54 Operators Revisited 55 Multiple Choice: if . . . else 61 The unless Statement 64 Expression Modifiers 65 Using Short-Circuited Evaluation 65 Looping Constructs 66 The while Loop 66 while (<STDIN>) 67 Infinite Loops 69 Looping Until 70 The for Loop 71 ■ CONTENTS vii The foreach Loop 71 do while and do until 72 Loop Control Constructs 74 Breaking Out 74 Going On to the Next 75 Reexecuting the Loop 76 Loop Labels 77 goto 79 Summary 79 Exercises 79 ■Chapter 4: Lists and Arrays 81 Lists 81 Simple Lists 82 More Complex Lists 83 Creating Lists Easily with qw// 84 Accessing List Values 87 Arrays 91 Assigning Arrays 91 Scalar vs. List Context 94 Adding to an Array 95 Accessing an Array 95 Summary 114 Exercises 114 ■Chapter 5: Hashes 115 Creating a Hash 115 Working with Hash Values 117 Hash in List Context 119 ■ CONTENTS CONTENTS viii Hash in Scalar Context 120 Hash Functions 121 The keys() Function 121 The values() Function 122 The each() Function 123 The delete() Function 123 The exists() Function 124 Hash Examples 125 Creating Readable Variables 125 “Reversing” Information 125 Counting Things 126 Summary 129 Exercises 129 ■Chapter 6: Subroutines/Functions 131 Understanding Subroutines 132 Defining a Subroutine 132 Invoking a Subroutine 133 Order of Declaration and Invoking Functions 134 Passing Arguments into Functions 137 Return Values 139 The return Statement 141 Understanding Scope 142 Global Variables 142 Introduction to Packages 144 Lexical Variables (aka Local Variables) 146 Some Important Notes on Passing Arguments 147 Function Arguments Passed by Reference 147 Lists Are One-Dimensional 149 [...]... collection of those Perl modules mentioned previously Other important Perl sites are listed here: • • www.theperlreview.com: The home of the Perl Review, an online Perl magazine • www.activestate.com: The home of Perl on Windows • xxvi www.pm.org: The Perl Mongers, a worldwide umbrella organization for Perl user groups • 1 www .perl. org: A site with tons of information about Perl www.perlarchive.com: Another... enhancements to Perl syntax that are being debated—the Todo file in the Perl source kit explains what’s currently on the table Perl 6 The future of Perl lies in Perl 6, a complete rewrite of the language The purpose of Perl 6 is to address the problems with Perl 5 and to create a language that can continue to grow and change in the future Larry Wall has this to say about Perl 6: Perl 5 was my rewrite of Perl. .. interesting things, as you’re about to see Perldoc Typing perldoc perl from a command prompt presents the Perl documentation table of contents and some basic information about Perl The pages you’re probably going to use the most are the Perl FAQ and perlfunc, which describes the built-in functions Because of this, perldoc has a special interface to these two pages perldoc -f allows you to see information... an acronym for this phrase – FMTEYWTKA ■ INTRODUCTION Newsgroups Perl has its own Usenet hierarchy, comp.lang .perl. * The groups in it are listed here: • comp.lang .perl. announce for Perl- related announcements: new modules, new versions of Perl, conferences, and so on • comp.lang .perl. misc for general Perl chat and questions • comp.lang .perl. moderated, which requires prior registration before posting... release tarball) Perl 2 expanded regular expression support, while Perl 3 enabled the language to deal with binary data Perl 4 was released so that the “Camel Book” (also known as Programming Perl by Larry Wall [O'Reilly & Associates, 2000]) could refer to a new version of Perl Perl 5 has seen some rather drastic changes in syntax, and some pretty fantastic extensions to the language Perl 5 is (more... in Perl 6 will be the introduction of Rakudo (http://www.rakudo.org) which is based on Parrot (http://www.parrotcode.org) Rakudo is the new runtime environment that is being developed from scratch for Perl 6, but it will not be limited to Perl 6—any bytecode-compiled language such as Tcl and Python can use it You can read all about the future of Perl at http://dev .perl. org /perl6 / and http://www .perl6 .org/... for a function Perl development is done in the open, on the perl5 -porters mailing list The perlbug program, shipped with Perl, can be used to report problems to the list, but it’s a good idea to check with someone first to make sure that it really is a problem and that it isn’t fixed in a later or development release of Perl Perl on the Web and the Network One of the most popular uses of Perl is CGI programming—that... to learn Perl and get an introduction to its power, this book is for you How This Book Is Organized Chapter 1—First Steps in Perl: The basics of Perl are introduced, including how to execute Perl code A simple first program is developed Chapter 2—Scalars: The most basic Perl data type, the scalar, is described Perl s arithmetic, logical, and string operators are explained, as are a few of Perl s simplest... snipped—try it yourself!): $ perldoc -f print print FILEHANDLE LIST print LIST print Prints a string or a list of strings Returns true if successful FILEHANDLE may be a scalar variable name, in which case [output snipped] Similarly, perldoc -q allows you to search the Perl FAQ for any regular expression or keyword $ perldoc -q reverse Found in /usr/lib /perl5 /5.10.1/pod/perlfaq4.pod How do I reverse... of Perl s niggly bits • comp.lang .perl. modules, for discussion and queries relating to creating and using Perl modules • comp.lang .perl. tk, for discussion and queries relating to the Tk graphical extensions IRC If you’ve got a more urgent mindbender, or just want to hang around like-minded individuals, come join #perl on Efnet (www.efnet.org) Make sure you read the channel rules (at http://pound .perl. org/RTFM/) . ROADMAP The Definitive Guide to Catalyst Pro Perl Linux System Administration Recipes Beginning Perl 3rd Ed Beginning Portable Shell Scripting Covers Perl 5.10 THIRD EDITION 7.5 x 9.25 spine. SOURCE Perl THIRD EDITION James Lee Perl for those who missed it the first time around: Learn about the duct tape for the web, the cloud and system administration Beginning Covers Perl 5.10 Beginning. appreciate Perl& apos;s versatility and functionality for solving simple and highly complex problems alike. Plus, Perl is one of the most enjoyable languages to use—programming in Perl is fun!