Teach Yourself
     Perl 5
        in 21 days

               David Till



CONTENTS

Introduction

Week 1   Week at a Glance

Day 1   Getting Started

Day 2   Basic Operators and Control Flow

Day 3   Understanding Scalar Values

Day 4   More Operators

Day 5   Lists and Array Variables

Day 6   Reading from and Writing to Files

Day 7   Pattern Matching

Week 1   Week 1 in Review

Week 2   Week 2 at a Glance

Day 8   More Control Structures

Day 9   Using Subroutines

Day 10   Associative Arrays

Day 11   Formatting Your Output

Day 12   Working with the File System

Day 13   Process, String, and Mathematical Functions

Day 14   Scalar-Conversion and List-Manipulation Functions

Week 2   Week 2 in Review

Week 3   Week 3 at a Glance

Day 15   System Functions

Day 16   Command-Line Options

Day 17   System Variables

Day 18   References in Perl 5

Day 19   Object-Oriented Programming in Perl

Day 20   Miscellaneous Features of Perl

Day 21   The Perl Debugger

Week 3   Week 3 in Review

Appendix A   Answers

Appendix B   ASCII Character Set

Credits



Copyright © 1996 by Sams Publishing

SECOND EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 0-672-30894-0 HTML conversion by :
    M/s. LeafWriters (India) Pvt. Ltd.
    Website : http://leaf.stpn.soft.net
    e-mail : [email protected]


Publisher and PresidentRichard K. Swadley Acquisitions ManagerGreg Wiegand
Development ManagerDean Miller Managing EditorCindy Morrow
Marketing ManagerJohn Pierce Assistant Marketing ManagerKristina Perry
Acquisitions EditorChris Denny Development EditorsAngelique Brittingham, Keith Davenport
Software Development Specialist Steve StraigerProduction Editor Tonya R. Simpson
Copy EditorKimberly K. Hannel Technical ReviewerElliotte Rusty Harold
Editorial CoordinatorBill Whitmer Technical Edit CoordinatorLynette Quinn
FormatterFrank Sinclair Editorial AssistantsCarol Ackerman, Andi Richter Rhonda, Tinch-Mize
Cover DesignerTim Amrhein Book DesignerGary Adair
Copy WriterPeter Fuller Production Team SupervisorBrad Chinn
ProductionMichael Brumitt, Charlotte Clapp, Jason Hand, Sonja Hart, Louisa Klucznik, Ayanna Lacey, Clint Lahnen, Paula Lowell, Laura Robbins, Bobbi Satterfield, Carol Sheehan, Chris Wilcox


Acknowledgments

I would like to thank the following people for their help:

I'd also like to thank all those friends of mine (you know who you are) who tolerated my going stir-crazy as my deadlines approached.

About the Authors

David Till

David Till is a technical writer working in Toronto, Ontario, Canada. He holds a master's degree in computer science from the University of Waterloo; programming languages was his major field of study. He also has worked in compiler development and on version-control software. He lists his hobbies as "writing, comedy, walking, duplicate bridge, and fanatical support of the Toronto Blue Jays."

He can be reached via e-mail at [email protected] or [email protected], or on the World Wide Web at http://www.interlog.com/~davet/.

Kamran Husain

Kamran Husain is a software consultant with experience in UNIX system programming. He has dabbled in all sorts of software for real-time systems applications, telecommunications, seismic data acquisition and navigation, X Window/Motif and Microsoft Windows applications. He refuses to divulge any more of his qualifications. Kamran offers consulting services and training classes through his company, MPS Inc., in Houston, Texas. He is an alumnus of the University of Texas at Austin.

You can reach Kamran through Sams Publishing or via e-mail at [email protected] or [email protected].


Introduction

This book is designed to teach you the Perl programming language in just 21 days. When you finish reading this book, you will have learned why Perl is growing rapidly in popularity: It is powerful enough to perform many useful, sophisticated programming tasks, yet it is easy to learn and use.

Who Should Read This Book?

No previous programming experience is required for you to learn everything you need to know about programming with Perl from this book. In particular, no knowledge of the C programming language is required. If you are familiar with other programming languages, learning Perl will be a snap. The only assumption this book does make is that you are familiar with the basics of using the UNIX operating system.

Special Features of This Book

This book contains some special elements that help you understand Perl features and concepts as they are introduced:

Syntax boxes explain some of the more complicated features of Perl, such as the control structures. Each syntax box consists of a formal definition of the feature followed by an explanation of the elements of the feature. Here is an example of a syntax box:

The syntax of the for statement is


for (expr1; expr2; expr3) {

        statement_block

}

expr1 is the loop initializer. It is evaluated only once, before the start of the loop.

expr2 is the conditional expression that terminates the loop. The conditional expression in expr2 behaves just like the ones in while and if statements: If its value is zero, the loop is terminated, and if its value is nonzero, the loop is executed.

statement_block is the collection of statements that is executed if (and when) expr2 has a nonzero value.

expr3 is executed once per iteration of the loop, and is executed after the last statement in statement_block is executed.

Don't try to understand this definition yet!

DO/DON'T boxes present the do's and don'ts for a particular task or feature. Here is an example of such a box:

DON'T confuse the | operator (bitwise OR) with the || operator (logical OR).
DO make sure you are using the proper bitwise operator. It's easy to slip and assume you want bitwise OR when you really want bitwise AND. (Trust me.

Notes are explanations of interesting properties of a particular program feature. Here is an example of a note:

NOTE
In left-justified output, the value being displayed appears at the left end of the value field. In right-justified output, the value being displayed appears at the right end of the value field.

Warnings warn you of programming pitfalls to avoid. Here is a typical warning:

You cannot use the last statement inside the do statement. The do statement, although it behaves like the other control structures, is actually implemented differently.

Tips are hints on how to write your Perl programs better. Here is an example of a tip:

TIP
It is a good idea to use all uppercase letters for your file variable names. This makes it easier to distinguish file variable names from other variable names and from reserved words.

Programming Examples

Each feature of Perl is illustrated by examples of its use. In addition, each chapter of this book contains many useful programming examples complete with explanations; these examples show you how you can use Perl features in your own programs.

Each example contains a listing of the program, the input required by and the output generated by the program, and an analysis of how the program works. Special icons are used to point out each part of the example: Type, Input-Output, and Analysis.

In the Input-Output example following Listing IN.1, there are some special typographic conventions. The input you enter is shown in bold monospace type, and the output generated by the system or the program is shown in plain monospace type. The system prompt ($ in the examples in this book) is shown so that you know when a command is to be entered on the command line.


Listing IN.1. A simple Perl program with comments.

1: #!/usr/local/bin/perl

2: # this program reads a line of input, and writes the line

3: # back out

4: $inputline = <STDIN>;    # read a line of input

5: print( $inputline );     # write the line out



$ programIN_1

This is a line of input.

This is a line of input.

$

Line 1 is the header comment. Lines 2 and 3 are comments, not executable lines of code. Line 4 reads a line of input. Line 5 writes the line of input on your screen.

End-of-Day Q& A and Workshop

Each day ends with a Q&A section containing answers to common questions relating to that day's material. There also is a Workshop at the end of each day that consists of quiz questions and programming exercises. The exercises often include BUG BUSTER exercises that help you spot some of the common bugs that crop up in Perl programs. The answers to these quiz questions as well as sample solutions for the exercises are presented in Appendix A, "Answers."

Conventions Used in This Book

This book uses different typefaces to help you differentiate between Perl code and regular English, and also to help you identify important concepts.

What You'll Learn in 21 Days

In your first week of learning Perl, you'll learn enough of the basics of Perl to write many useful Perl programs. Here's a summary of what you'll learn in Week 1:

Day 1, "Getting Started," tells you how to get Perl, how to run Perl programs, and how to read from your keyboard and write to your screen.
Day 2, "Basic Operators and Control Flow," teaches you about simple arithmetic, how to assign a value to a scalar variable, and how to control execution using conditional statements.
Day 3, "Understanding Scalar Values," teaches you about integers, floating-point numbers, and character strings. It also shows you that all three are interchangeable in Perl.
Day 4, "More Operators," tells you all about operators and expressions in Perl and talks about operator associativity and precedence.
Day 5, "Lists and Array Variables," introduces you to lists, which are collections of values, and to array variables, which store lists.
Day 6, "Reading from and Writing to Files," tells you how to interact with your file system by reading from input files, writing to output files, and testing for particular file attributes.
Day 7, "Pattern Matching," describes pattern-matching in Perl and shows how you can substitute values and translate sets of characters in text strings.

By the end of Week 2, you'll have mastered almost all the features of Perl; you'll also have learned about many of the library functions supplied with the language. Here's a summary of what you'll learn:

Day 8, "More Control Structures," discusses the control flow statements not previously covered.
Day 9, "Using Subroutines," shows how you can break your program into smaller, more manageable, chunks.
Day 10, "Associative Arrays," introduces one of the most powerful and useful constructs in Perl-arrays-and it shows how you can use these arrays to simulate other data structures.
Day 11, "Formatting Your Output," shows how you can use Perl to produce tidy reports.
Day 12, "Working with the File System," shows how you can interact with your system's directory structure.
Day 13, "Process, String, and Mathematical Functions," describes the library functions that interact with processes running on the system. It also describes the functions that perform trigonometric and other mathematical operations, and the functions that operate on strings.
Day 14, "Scalar-Conversion and List-Manipulation Functions," describes the library functions that convert values from one form to another and the functions that work with lists and array variables.

By the end of Week 3, you'll know all the features and capabilities of Perl. It covers the rest of the Perl library functions and describes some of the more esoteric concepts of the language. Here's a summary of what you'll learn:

Day 15, "System Functions," describes the functions that manipulate the Berkeley UNIX and UNIX System V environments.
Day 16, "Command-Line Options," describes the options you can supply with Perl to control how your program runs.
Day 17, "System Variables," describes the built-in variables that are included automatically as part of every Perl program.
Day 18, "References in Perl 5," describes the pointer and reference features of Perl 5, including multi-dimensional arrays.
Day 19, "Object-Oriented Programming in Perl," describes the object-oriented capabilities added to Perl 5. These enable you to hide information and divide your program into individual file modules.
Day 20, "Miscellaneous Features of Perl," covers some of the more exotic or obscure features of the language.
Day 21, "The Perl Debugger," shows you how to use the Perl debugger to discover errors quickly.