Teach Yourself Perl 5 In 21 Days - Anarcho-Copy

Transcription

Teach Yourself Perl 5 in 21 daysDavid TillTable of Contents:Introduction Who Should Read This Book?Special Features of This BookProgramming ExamplesEnd-of-Day Q& A and WorkshopConventions Used in This BookWhat You'll Learn in 21 DaysWeek 1 Week at a Glance Where You're GoingDay 1 Getting Started What Is Perl?How Do I Find Perl? Where Do I Get Perl? Other Places to Get PerlA Sample Perl ProgramRunning a Perl Program If Something Goes WrongThe First Line of Your Perl Program: How Comments Work CommentsLine 2: Statements, Tokens, and STDIN Statements and Tokens Tokens and White Space What the Tokens Do: Reading from Standard InputLine 3: Writing to Standard Output Function Invocations and ArgumentsError MessagesInterpretive Languages Versus Compiled LanguagesSummaryQ&A

Workshop Quiz ExercisesDay 2 Basic Operators and Control Flow Storing in Scalar Variables Assignment The Definition of a Scalar Variable Scalar Variable Syntax Assigning a Value to a Scalar VariablePerforming Arithmetic Example of Miles-to-Kilometers Conversion The chop Library FunctionExpressions Assignments and ExpressionsOther Perl OperatorsIntroduction to Conditional StatementsThe if Statement The Conditional Expression The Statement Block Testing for Equality Using Other Comparison OperatorsTwo-Way Branching Using if and elseMulti-Way Branching Using elsifWriting Loops Using the while StatementNesting Conditional StatementsLooping Using the until StatementSummaryQ&AWorkshop Quiz ExercisesDay 3 Understanding Scalar Values What Is a Scalar Value?Integer Scalar Values Integer Scalar Value LimitationsFloating-Point Scalar Values Floating-Point Arithmetic and Round-Off ErrorUsing Octal and Hexadecimal Notation Decimal Notation Octal Notation

Hexadecimal Notation Why Bother?Character Strings Using Double-Quoted Strings Escape Sequences Single-Quoted StringsInterchangeability of Strings and Numeric Values Initial Values of Scalar VariablesSummaryQ&AWorkshop Quiz Exercises Day 4 More Operators Using the Arithmetic Operators Exponentiation The Remainder Operator Unary NegationUsing Comparison Operators Integer-Comparison Operators String-Comparison Operators String Comparison Versus Integer Comparison Comparison and Floating-Point NumbersUsing Logical Operators Evaluation Within Logical Operators Logical Operators as SubexpressionsUsing Bit-Manipulation Operators What Bits Are and How They Are Used The Bit-Manipulation OperatorsUsing the Assignment Operators Assignment Operators as SubexpressionsUsing Autoincrement and Autodecrement The Autoincrement Operator Pre-Increment The Autoincrement Operator Post-Increment The Autodecrement Operator Using Autoincrement With StringsThe String Concatenation and Repetition Operators The String-Concatenation Operator The String-Repetition Operator Concatenation and AssignmentOther Perl Operators

The Comma Operator The Conditional OperatorThe Order of Operations Precedence Associativity Forcing Precedence Using ParenthesesSummaryQ&AWorkshop Quiz Exercises Day 5 Lists and Array Variables Introducing ListsScalar Variables and Lists Lists and String SubstitutionStoring Lists in Array VariablesAccessing an Element of an Array Variable More Details on Array Element NamesUsing Lists and Arrays in Perl Programs Using Brackets and Substituting for VariablesUsing List Ranges Expressions and List RangesMore on Assignment and Array Variables Copying from One Array Variable to Another Using Array Variables in Lists Substituting for Array Variables in Strings Assigning to Scalar Variables from Array VariablesRetrieving the Length of a ListUsing Array Slices Using List Ranges in Array-Slice Subscripts Using Variables in Array-Slice Subscripts Assigning to Array Slices Overlapping Array Slices Using the Array-Slice Notation as a ShorthandReading an Array from the Standard Input FileArray Library Functions Sorting a List or Array Variable Reversing a List or Array Variable Using chop on Array Variables Creating a Single String from a List Splitting a String into a List

Other List-Manipulation FunctionsSummaryQ&AWorkshop Quiz Exercises Day 6 Reading from and Writing to Files Opening a File The File Variable The Filename The File Mode Checking Whether the Open SucceededReading from a File File Variables and the Standard Input File Terminating a Program Using die Reading into Array VariablesWriting to a File The Standard Output File Variable Merging Two Files into OneRedirecting Standard Input and Standard OutputThe Standard Error FileClosing a FileDetermining the Status of a File File-Test Operator Syntax Available File-Test Operators More on the -e Operator Testing for Read Permission-the -r Operator Checking for Other Permissions Checking for Empty Files Using File-Test Operators with File VariablesReading from a Sequence of Files Reading into an Array VariableUsing Command-Line Arguments as Values ARGV and the OperatorOpening PipesSummaryQ&AWorkshop Quiz Exercises

Day 7 Pattern Matching IntroductionThe Match Operators Match-Operator PrecedenceSpecial Characters in Patterns The Character The [] Special Characters The * and ? Special Characters Escape Sequences for Special Characters Matching Any Letter or Number Anchoring Patterns Variable Substitution in Patterns Excluding Alternatives Character-Range Escape Sequences Matching Any Character Matching a Specified Number of Occurrences Specifying Choices Reusing Portions of Patterns Pattern-Sequence Scalar Variables Special-Character Precedence Specifying a Different Pattern DelimiterPattern-Matching Options Matching All Possible Patterns Ignoring Case Treating the String as Multiple Lines Evaluating a Pattern Only Once Treating the String as a Single Line Using White Space in PatternsThe Substitution Operator Using Pattern-Sequence Variables in Substitutions Options for the Substitution Operator Evaluating a Pattern Only Once Treating the String as Single or Multiple Lines Using White Space in Patterns Specifying a Different DelimiterThe Translation Operator Options for the Translation OperatorExtended Pattern-Matching Parenthesizing Without Saving in Memory Embedding Pattern Options Positive and Negative Look-Ahead Pattern CommentsSummary

Q&AWorkshop Quiz ExercisesWeek 1 Week 1 in ReviewWeek 2 Week 2 at a Glance Where You're GoingDay 8 More Control Structures Using Single-Line Conditional Statements Problems with Single-Line Conditional StatementsLooping Using the for Statement Using the Comma Operator in a for StatementLooping Through a List: The foreach Statement The foreach Local Variable Changing the Value of the Local Variable Using Returned Lists in the foreach StatementThe do StatementExiting a Loop Using the last StatementUsing next to Start the Next Iteration of a LoopThe redo StatementUsing Labeled Blocks for Multilevel Jumps Using next and redo with LabelsThe continue BlockThe goto StatementSummaryQ&AWorkshop Quiz ExercisesDay 9 Using Subroutines What Is a Subroutine?Defining and Invoking a Subroutine Forward References to SubroutinesReturning a Value from a Subroutine Return Values and Conditional ExpressionsThe return Statement

Using Local Variables in Subroutines Initializing Local VariablesPassing Values to a Subroutine Passing a List to a SubroutineCalling Subroutines from Other SubroutinesRecursive SubroutinesPassing Arrays by Name Using AliasesUsing the do Statement with SubroutinesSpecifying the Sort OrderPredefined Subroutines Creating Startup Code Using BEGIN Creating Termination Code Using END Handling Non-Existent Subroutines Using AUTOLOADSummaryQ&AWorkshop Quiz ExercisesDay 10 Associative Arrays Limitations of Array VariablesDefinitionReferring to Associative Array ElementsAdding Elements to an Associative ArrayCreating Associative ArraysCopying Associative Arrays from Array VariablesAdding and Deleting Array ElementsListing Array Indexes and ValuesLooping Using an Associative ArrayCreating Data Structures Using Associative Arrays Linked Lists Structures Trees Databases Example: A Calculator ProgramSummaryQ&AWorkshop Quiz ExercisesDay 11 Formatting Your Output

Defining a Print FormatDisplaying a Print FormatDisplaying Values in a Print Format Creating a General-Purpose Print Format Choosing a Value-Field Format Printing Value-Field Characters Using the Multiline Field FormatWriting to Other Output Files Saving the Default File VariableSpecifying a Page Header Changing the Header Print FormatSetting the Page Length Using print with PaginationFormatting Long Character Strings Eliminating Blank Lines When Formatting Supplying an Indefinite Number of LinesFormatting Output Using printfSummaryQ&AWorkshop Quiz ExercisesDay 12 Working with the File System File Input and Output Functions Basic Input and Output Functions Skipping and Rereading Data System Read and Write Functions Reading Characters Using getc Reading a Binary File Using binmodeDirectory-Manipulation Functions The mkdir Function The chdir Function The opendir Function The closedir Function The readdir Function The telldir and seekdir Functions The rewinddir Function The rmdir FunctionFile-Attribute Functions File-Relocation Functions Link and Symbolic Link Functions

File-Permission Functions Miscellaneous Attribute FunctionsUsing DBM Files The dbmopen Function The dbmclose FunctionSummaryQ&AWorkshop Quiz Exercises Day 13 Process, String, and Mathematical Functions Process- and Program-Manipulation Functions Starting a Process Terminating a Program or Process Execution Control Functions Miscellaneous Control FunctionsMathematical Functions The sin and cos Functions The atan2 Function The sqrt Function The exp Function The log Function The abs Function The rand and srand FunctionsString-Manipulation Functions The index Function The rindex Function The length Function Retrieving String Length Using tr The pos Function The substr Function The study Function Case Conversion Functions The quotemeta Function The join Function The sprintf FunctionSummaryQ&AWorkshop Quiz Exercises

Day 14 Scalar-Conversion and List-Manipulation Functions The chop FunctionThe chomp FunctionThe crypt FunctionThe hex FunctionThe int FunctionThe oct Function The oct Function and Hexadecimal IntegersThe ord and chr FunctionsThe scalar FunctionThe pack Function The pack Function and C Data TypesThe unpack Function Unpacking Strings Skipping Characters When Unpacking The unpack Function and uuencodeThe vec FunctionThe defined FunctionThe undef FunctionArray and List Functions The grep Function The splice Function The shift Function The unshift Function The push Function The pop Function Creating Stacks and Queues The split Function The sort and reverse Functions The map Function The wantarray FunctionAssociative Array Functions The keys Function The values Function The each Function The delete Function The exists FunctionSummaryQ&AWorkshop Quiz Exercises

Week 2 Week 2 in ReviewWeek 3 Week 3 at a Glance Where You're GoingDay 15 System Functions System Library Emulation Functions The getgrent Function The setgrent and endgrent Functions The getgrnam Function The getgrid Function The getnetent Function The getnetbyaddr Function The getnetbyname Function The setnetent and endnetent Functions The gethostbyaddr Function The gethostbyname Function The gethostent, sethostent, and endhostent Functions The getlogin Function The getpgrp and setpgrp Functions The getppid Function The getpwnam Function The getpwuid Function The getpwent Function The setpwent and endpwent Functions The getpriority and setpriority Functions The getprotoent Function The getprotobyname and getprotobynumber Functions The setprotoent and endprotoent Functions The getservent Function The getservbyname and getservbyport Functions The setservent and endservent Functions The chroot Function The ioctl Function The alarm Function Calling the System select Function The dump FunctionSocket-Manipulation Functions The socket Function The bind Function The listen Function

The accept Function The connect Function The shutdown Function The socketpair Function The getsockopt and setsockopt Functions The getsockname and getpeername FunctionsThe UNIX System V IPC Functions IPC Functions and the require Statement The msgget Function The msgsnd Function The msgrcv Function The msgctl Function The shmget Function The shmwrite Function The shmread Function The shmctl Function The semget Function The semop Function The semctl FunctionSummaryQ&AWorkshop Quiz Exercises Day 16 Command-Line Options Specifying Options Specifying Options on the Command Line Specifying an Option in the ProgramThe -v Option: Printing the Perl Version NumberThe -c Option: Checking Your SyntaxThe -w Option: Printing Warnings Checking for Possible Typos Checking for Redefined Subroutines Checking for Incorrect Comparison OperatorsThe -e Option: Executing a Single-Line ProgramThe -s Option: Supplying Your Own Command-Line Options The -s Option and Other Command-Line ArgumentsThe -P Option: Using the C Preprocessor The C Preprocessor: A Quick OverviewThe -I Option: Searching for C Include FilesThe -n Option: Operating on Multiple Files

The -p Option: Operating on Files and PrintingThe -i Option: Editing Files Backing Up Input Files Using the -i OptionThe -a Option: Splitting LinesThe -F Option: Specifying the Split PatternThe -0 Option: Specifying Input End-of-LineThe -l Option: Specifying Output End-of-LineThe -x Option: Extracting a Program from a MessageMiscellaneous Options The -u Option The -U Option The -S Option The -D Option The -T Option: Writing Secure ProgramsThe -d Option: Using the Perl DebuggerSummaryQ&AWorkshop Quiz ExercisesDay 17 System Variables Global Scalar Variables The Default Scalar Variable: The Program Name: 0 The User ID: and The Group ID: ( and ) The Version Number: ] The Input Line Separator: / The Output Line Separator: The Output Field Separator: , The Array Element Separator: " The Number Output Format: # The eval Error Message: @ The System Error Code: ? The System Error Message: ! The Current Line Number: . Multiline Matching: * The First Array Subscript: [ Multidimensional Associative Arrays and the ; Variable The Word-Break Specifier: : The Perl Process ID:

The Current Filename: ARGV The Write Accumulator: A The Internal Debugging Value: D The System File Flag: F Controlling File Editing Using I The Format Form-Feed Character: L Controlling Debugging: P The Program Start Time: T Suppressing Warning Messages: W The X VariablePattern System Variables Retrieving Matched Subpatterns Retrieving the Entire Pattern: & Retrieving the Unmatched Text: the and ' Variables The VariableFile System Variables The Default Print Format: Specifying Page Length: Lines Remaining on the Page: The Page Header Print Format: Buffering Output: The Current Page Number: %Array System Variables The @ Variable The @ARGV Variable The @F Variable The @INC Variable The %INC Variable The %ENV Variable The %SIG VariableBuilt-In File Variables STDIN, STDOUT, and STDERR ARGV DATA The Underscore File VariableSpecifying System Variable Names as WordsSummaryQ&AWorkshop Quiz Exercises Day 18 References in Perl 5

Introduction to ReferencesUsing ReferencesUsing the Backslash OperatorReferences and ArraysMultidimensional ArraysReferences to Subroutines Using Subroutine TemplatesUsing Subroutines to Work with Multiple Arrays Pass By Value or By Reference?References to File Handles What Does the *variable Operator Do?Using Symbolic References Again Declaring Variables with Curly BracesMore on Hard Versus Symbolic ReferencesFor More InformationSummaryQ&AWorkshop QuizExercisesDay 19 Object-Oriented Programming in Perl An Introduction to Modules The Three Important RulesClasses in PerlCreating a ClassBlessing a Constructor Instance VariablesMethodsExporting MethodsInvoking MethodsOverridesDestructorsInheritanceOverriding MethodsA Few Comments About Classes and Objects in PerlSummaryQ&AWorkshop Quiz Exercises

Day 20 Miscellaneous Features of Perl The require Function The require Function and Subroutine Libraries Using require to Specify a Perl VersionThe #array Variables Controlling Array Length Using #arrayAlternative String Delimiters Defining Strings Using Special Internal ValuesUsing Back Quotes to Invoke System CommandsPattern Matching Using ? and the reset Function Using reset with VariablesOther Features of the Operator Scalar Variable Substitution and Creating a List of FilenamesGlobal Indirect References and AliasesPackages Defining a Package Switching Between Packages The main Package Referring to One Package from Another Specifying No Current Package Packages and Subroutines Defining Private Data Using Packages Packages and System Variables Accessing Symbol TablesModules Creating a Module Importing Modules Into Your Program Using Predefined ModulesUsing Perl in C ProgramsPerl and CGI ScriptsTranslators and Other Supplied CodeSummaryQ&AWorkshop Quiz ExercisesDay 21 The Perl Debugger Entering and Exiting the Perl Debugger

Entering the Debugger Exiting the DebuggerListing Your Program The l command The - Command The w Command The // and ? Commands The S CommandStepping Through Programs The s Command The n Command The f command The Carriage-Return Command The r CommandDisplaying Variable Values The X Command The V CommandBreakpoints The b Command The c Command The L Command and Breakpoints The d and D CommandsTracing Program ExecutionLine Actions The a Command The A Command The and Commands Displaying Line Actions Using the L CommandOther Debugging Commands Executing Other Perl Statements The H Command: Listing Preceding Commands The ! Command: Executing Previous Commands The T Command: Stack Tracing The p Command: Printing an Expression The Command: Defining Aliases Predefining Aliases The h Command: Debugger HelpSummaryQ&AWorkshop Quiz Week 3 Week 3 in Review

Appendix A Answers Answers for Day 1, "Getting Started" Quiz ExercisesAnswers for Day 2, "Basic Operators and Control Flow" Quiz ExercisesAnswers for Day 3, "Understanding Scalar Values" Quiz ExercisesAnswers for Day 4, "More Operators" Quiz ExercisesAnswers for Day 5, "Lists and Array Variables" Quiz ExercisesAnswers for Day 6, "Reading from and Writing to Files" Quiz ExercisesAnswers for Day 7, "Pattern Matching" Quiz ExercisesAnswers for Day 8, "More Control Structures" Quiz ExercisesAnswers for Day 9, "Using Subroutines" Quiz ExercisesAnswers for Day 10, "Associative Arrays" Quiz ExercisesAnswers for Day 11, "Formatting Your Output" Quiz ExercisesAnswers for Day 12, "Working with the File System" Quiz ExercisesAnswers for Day 13, "Process, String, and Mathematical Functions" Quiz ExercisesAnswers for Day 14, "Scalar-Conversion and List-Manipulation Functions" Quiz

ExercisesAnswers for Day 15, "System Functions" Quiz ExercisesAnswers for Day 16, "Command-Line Options" Quiz ExercisesAnswers for Day 17, "System Variables" Quiz ExercisesAnswers for Day 18, "References inPerl 5" Quiz ExercisesAnswers for Day 19, "Object-Oriented Programming in Perl" Quiz ExercisesAnswers for Day 20, "Miscellaneous Features of Perl" Quiz ExercisesAnswers for Day 21, "The Perl Debugger" Quiz Appendix B ASCII Character SetCreditsCopyright 1996 by Sams PublishingSECOND EDITIONAll rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted byany means, electronic, mechanical, photocopying, recording, or otherwise, without written permission fromthe 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 assumeno responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the useof 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.nete-mail : leafwriters@leaf.stpn.soft.netPublisher and President Richard K. SwadleyDevelopment Manager Dean MillerMarketing ManagerJohn PierceAcquisitions EditorChris DennyAcquisitions ManagerManaging EditorAssistant MarketingManagerDevelopment EditorsSoftware DevelopmentSpecialistCopy EditorEditorial CoordinatorSteve StraigerProduction EditorKimberly K. HannelBill WhitmerFormatterFrank SinclairTechnical ReviewerTechnical EditCoordinatorEditorial AssistantsCover DesignerCopy WriterTim AmrheinPeter FullerProductionGreg WiegandCindy MorrowKristina PerryAngelique Brittingham,Keith DavenportTonya R. SimpsonElliotte Rusty HaroldLynette QuinnCarol Ackerman, AndiRichter Rhonda, TinchMizeGary AdairBrad ChinnBook DesignerProduction TeamSupervisorMichael Brumitt, Charlotte Clapp, Jason Hand, Sonja Hart, Louisa Klucznik,Ayanna Lacey, Clint Lahnen, Paula Lowell, Laura Robbins, Bobbi Satterfield,Carol Sheehan, Chris WilcoxAcknowledgmentsI would like to thank the following people for their help: David Macklem at Sietec Open Systems for allowing me to take the time off to work on the firstedition of this bookEveryone at Sams Publishing, for their efforts and encouragementJim Gardner, for telling the people at Sams Publishing about meI'd also like to thank all those friends of mine (you know who you are) who tolerated my going stir-crazy asmy deadlines approached.About the AuthorsDavid TillDavid 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. Healso 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 am671@freenet.toronto.on.ca or davet@klg.com, or on theWorld Wide Web at http://www.interlog.com/ davet/.Kamran HusainKamran Husain is a software consultant with experience in UNIX system programming. He has dabbled inall sorts of software for real-time systems applications, telecommunications, seismic data acquisition andnavigation, X Window/Motif and Microsoft Windows applications. He refuses to divulge any more of hisqualifications. Kamran offers consulting services and training classes through his company, MPS Inc., inHouston, Texas. He is an alumnus of the University of Texas at Austin.You can reach Kamran through Sams Publishing or via e-mail at khusain@neosoft.com ormpsi@aol.com.IntroductionThis book is designed to teach you the Perl programming language in just 21 days. When you finish readingthis book, you will have learned why Perl is growing rapidly in popularity: It is powerful enough to performmany 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 aboutprogramming with Perl from this book. In particular, no knowledge of the C programming language isrequired. If you are familiar with other programming languages, learning Perl will be a snap. The onlyassumption this book does make is that you are familiar with the basics of using the UNIX operating system.Special Features of This BookThis book contains some special elements that help you understand Perl features and concepts as they areintroduced: Syntax boxesDO/DON'T boxesNotesWarningsTipsSyntax boxes explain some of the more complicated features of Perl, such as the control structures. Eachsyntax 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 isfor (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 behavesjust like the ones in while and if statements: If its value is zero, the loop is terminated, and if its value isnonzero, the loop is executed.statement block is the collection of statements that is executed if (and when) expr2 has a nonzerovalue.expr3 is executed once per iteration of the loop, and is executed after the last statement instatement 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 abox: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 youwant 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 anote:NOTEIn left-justified output, the value being displayed appears at the leftend of the value field. In right-justified output, the value beingdisplayed 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 dostatement, although it behaves like the other control structures, isactually implemented differently.Tips are hints on how to write your Perl programs better. Here is an example of a tip:TIPIt is a good idea to use all uppercase letters for your file variablenames. This makes it easier to distinguish file variable names fromother variable names and from reserved words.Programming ExamplesEach feature of Perl is illustrated by examples of its use. In addition, each chapter of this book containsmany useful programming examples complete with explanations; these examples show you how you can usePerl features in your own programs.Each example contains a listing of the program, the input required by and the output generated by theprogram, and an analysis of how the program works. Special icons are used to point out each part of theexample: Type, Input-Output, and Analysis.In the Input-Output example following Listing IN.1, there are some special typographic conventions. Theinput you enter is shown in bold monospace type, and the output generated by the system or theprogram is shown in plain monospace type. The system prompt ( in the examples in this book) isshown 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/perl2: # this program reads a line of input, and writes the line3: # back out4: inputline STDIN ;# read a line of input

5: print( inputline );# write the line out programIN 1This 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 4reads a line of input. Line 5 writes the line of input on your screen.End-of-Day Q& A and WorkshopEach 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 cropup in Perl programs. The answers to these quiz questions as well as sample solutions for the exercises arepresented in Appendix A, "Answers."Conventions Used in This BookThis book uses different typefaces to help you differentiate between Perl code and regular English, and alsoto help you identify important concepts. Actual Perl code is typeset in a special monospace font. You'll see this font used in listings and theInput-Output examples, as well as in code snippets. In the explanations of Perl features, commands,filenames, statements, variables, and any text you see on the screen also are typeset in this font.Command input and anything that you are supposed to enter appears in a bold monospace font.You'll see this mainly in the Input-Output examples.Placeholders in syntax descriptions appear in an italic monospace font. Replace the placeholderwith the actual filename, parameter, or whatever element it represents.Italics highlight technical terms when they first appear in the text and are sometimes used toemphasize important points.What You'll Learn in 21 DaysIn your first week of learning Perl, you'll learn enough of the basics of Perl to write many useful Perlprograms. 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 toassign 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 talksabout operator associativity and precedence.Day 5, "Lists a

Teach Yourself Perl 5 in 21 days David Till Table of Contents: Introduction Who Should Read This Book? Special Features of This Book Programming Examples End-of-Day Q& A and Workshop Conventions Used in This Book What You'll Learn in 21 Days Week 1 Week at a Glance Where You're Going Day 1 Getting Started What Is Perl?