1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly intermediate perl mar 2006 ISBN 0596102062

569 124 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 569
Dung lượng 1,79 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

To use the book, you just need to be familiar with the material in Learning Perl and have ambition to go further.. Intermediate Perl is about learning to use Perl as a programming langua

Trang 1

By brian d foy, Tom Phoenix, Randal L Schwartz

Publisher: O'Reilly Pub Date: March 2006 Print ISBN-10: 0-596-10206-2 Print ISBN-13: 978-0-59-610206-7 Pages: 278

Table of Contents | Index

Perl is a versatile, powerful programming language used in a variety of disciplines, ranging from system administration to web programming to database manipulation One slogan of

Trang 2

be small enough to be read in just an hour or two, ending with a series of exercises to help you practice what you've learned To use the book, you just need to be familiar with the

material in Learning Perl and have ambition to go further.

Perl is a different language to different people It is a quick scripting tool for some, and a fully-featured object-oriented language for others It is used for everything from

performing quick global replacements on text files, to crunching huge, complex sets of scientific data that take weeks to process Perl is what you make of it But regardless of what you use Perl for, this book helps you do it more effectively, efficiently, and elegantly.

Intermediate Perl is about learning to use Perl as a programming language, and not just a

scripting language This is the book that turns the Perl dabbler into the Perl programmer.

Trang 3

By brian d foy, Tom Phoenix, Randal L Schwartz

Publisher: O'Reilly Pub Date: March 2006 Print ISBN-10: 0-596-10206-2 Print ISBN-13: 978-0-59-610206-7 Pages: 278

Trang 9

most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 or

Trang 10

ISBN: 0-596-10206-2

[M]

Trang 11

Perl's object-oriented (OO) mechanism is classic

prestidigitation It takes a collection of Perl's existing non-OOfeatures, such as packages, references, hashes, arrays,

subroutines, and modules, and thenwith nothing up its

sleevemanages to conjure up fully functional objects, classes,and methods, seemingly out of nowhere

That's a great trick It means you can build on your existing Perlknowledge and ease your way into OO Perl development,

without first needing to conquer a mountain of new syntax ornavigate an ocean of new techniques It also means you canprogressively fine-tune OO Perl to meet your own needs, byselecting from the existing constructs the one that best suitsyour task

But there's a problem Since Perl co-opts packages, references,hashes, arrays, subroutines, and modules as the basis for its

OO mechanism, to use OO Perl you already need to understandpackages, references, hashes, arrays, subroutines, and

modules

And there's the rub The learning curve hasn't been eliminated;it's merely been pushed back half a dozen steps

So then, how are you going to learn everything you need toknow about non-OO Perl so you can start to learn everythingyou need to know about OO Perl?

This book is the answer In the following pages, Randal draws

on two decades of using Perl, and four decades of watching

Gilligan's Island and Mr Ed, to explain each of the components

of Perl that collectively underpin its OO features And, betterstill, he then goes on to show exactly how to combine thosecomponents to create useful classes and objects

Trang 12

And that's straight from the horse's mouth

Damian Conway, May 2003

Trang 13

reference And like Learning Perl, we've developed the material

in this book for a teaching environment and used it in that

setting, including for our own use at Stonehenge ConsultingServices, as we conduct on-site and open-enrollment trainings.You don't have to be a Unix guru, or even a Unix user, to benefit

Trang 14

just need to be familiar with the material in Learning Perl and

have the ambition to go further

Trang 15

You should read this book from front to back, stopping to do theexercises Each chapter builds on preceding chapters, and we'llassume that you know the material from those chapters as wediscuss new topics

Chapter 4, Introduction to References

Introduce a level of redirection to allow the same code tooperate on different sets of data

Trang 16

Learn how Perl manages to keep track of pointers to data,and an introduction to anonymous data structures and

autovivification

Chapter 6, Manipulating Complex Data Structures

Create, access, and print arbitrarily deep and nested datastructures, including arrays of arrays and hashes of hashes

Chapter 7, Subroutine References

Capture behavior as an anonymous subroutine that youcreate dynamically and execute later

Chapter 8, Filehandle References

Store filehandles in scalar variables that you can easily passaround your program or store in data structures

Trang 18

Share your work with the world by uploading it to CPAN

Appendix, Answers to Exercises

Where to go to get answers

Trang 20

This book is here to help you get your job done In general, youmay use the code in this book in your programs and

documentation You do not need to contact O'Reilly for

permission unless you're reproducing a significant portion of thecode For example, writing a program that uses several chunks

of code from this book does not require permission Selling or

distributing a CD-ROM of examples from O'Reilly books does

require permission Answering a question by citing this bookand quoting example code does not require permission

Incorporating a significant amount of example code from this

book into your product's documentation does require

permission

We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For

example: Intermediate Perl, by Randal L Schwartz, brian d foy,

10206-2

and Tom Phoenix Copyright 2006 O'Reilly Media, Inc., 0-596-If you feel your use of code examples falls outside fair use orthe permission given above, feel free to contact us at

permissions@oreilly.com

Trang 21

Please address comments and questions concerning this book tothe publisher:

http://www.oreilly.com/catalog/intermediateperl

To comment or ask technical questions about this book, sendemail to:

bookquestions@oreilly.com

For more information about books, conferences, Resource

Centers, and the O'Reilly Network, see the O'Reilly web site at:

http://www.oreilly.com

Trang 22

When you see a Safari® Enabled icon on the cover ofyour favorite technology book, it means the book is availableonline through the O'Reilly Network Safari Bookshelf Safari

offers a solution that's better than e-books It's a virtual librarythat lets you easily search thousands of top technology books,cut and paste code samples, download chapters, and find quickanswers when you need the most accurate, current information.Try it for free at http://safari.oreilly.com

Trang 23

From Randal In the preface of the first edition of Learning

Perl, I acknowledged the Beaverton McMenamin's Cedar Hills

Pub[*] just down the street from my house for the "rent-freebooth-office space" while I wrote most of the draft on my

Powerbook 140 Well, like wearing your lucky socks every daywhen your favorite team is in the play-offs, I wrote nearly all ofthis book (including these words) at the same brewpub, in

hopes that the light of success of the first book will shine on metwice (As I update this preface for the second edition, I can seethat my lucky socks do indeed work!)

[*] http://www.mcmenamins.com/

This McM's has the same great local microbrew beer and greasysandwiches, but they've gotten rid of my favorite pizza bread,replacing it with new items like marionberry cobbler (a localtreat) and spicy jambalaya (And they added two booths andput in some pool tables.) Also, instead of the Powerbook 140,I'm using a Titanium Powerbook, with 1,000 times more disk,

500 times more memory, and a 200-times-faster CPU running areal Unix-based operating system (OS X) instead of the limitedMac OS I also uploaded all of the draft sections (including thisone) over my 144K cell-phone modem and emailed them

directly to the reviewers, instead of having to wait to rush home

to my 9600-baud external modem and phone line How timeshave changed!

So, thanks once again to the staff of the McMenamin's CedarHills Pub for the booth space and hospitality

Like the fourth edition of Learning Perl, I also owe much of what

I'm saying here and how I'm saying it to the students of

Stonehenge Consulting Services, who have given me

Trang 24

awkwardly constructed questions) when I was exceeding the

"huh?" factor threshold With that feedback over many dozens

of presentations, I was able to keep refining and refactoring thematerials that paved the way for this book

Speaking of which, those materials started as a half-day

"What's new in Perl 5?" summary commissioned by Margie

Levine of Silicon Graphics, in addition to my frequently

presented on-site, four-day Llama course (targeted primarily forPerl Version 4 at the time) Eventually, I got the idea to beef upthose notes into a full course and enlisted fellow Stonehengepresenter Joseph Hall for the task (He's the one who selectedthe universe from which the examples are drawn.) Joseph

employee of the month" so often that I may have to finally give

up my preferred parking space Tom manages the materials(just as Tad manages operations) so I can focus on being thepresident and the janitor of Stonehenge

Tom Phoenix contributed most exercises in this book and a

timely set of review notes during my writing process, includingentire paragraphs for me to just insert in place of the drivel Ihad written We work well as a team, both in the classroom and

in our joint writing efforts It is for this effort that we've

acknowledged Tom as a coauthor, but I'll take direct blame forany parts of the book you end up hating: none of that couldhave possibly been Tom's fault

And last but not least, a special thanks to my business partner,

Trang 25

Of course, a book is nothing without a subject and a distributionchannel, and for that I must acknowledge longtime associatesLarry Wall and Tim O'Reilly Thanks, guys, for creating an

industry that has paid for my essentials, discretionary

purchases, and dreams for nearly 15 years

And, as always, a special thanks to Lyle and Jack for teaching

me nearly everything I know about writing and convincing methat I was much more than a programmer who might learn towrite: I was also a writer who happened to know how to

program Thank you

And to you, the reader of this book, for whom I toiled away thecountless hours while sipping a cold microbrew and scarfingdown a piece of incredible cheesecake, trying to avoid spilling

on my laptop keyboard: thank you for reading what I've

written I sincerely hope I've contributed (in at least a smallway) to your Perl proficiency If you ever meet me on the

Special non-Perl thanks to Stacey, Buster, Mimi, Roscoe, Amelia,Lila, and everyone else who tried to distract me while I was

Trang 26

From Both of Us Thanks to our reviewers, David H Adler,

Stephen Jenkins, Kevin Meltzer, Matthew Musgrove, AndrewSavige, and Ricardo Signes, for providing comments on the

draft of this book

Thanks also to our many students who have let us know whatparts of the course material have needed improvement over theyears It's because of you that we're all so proud of it today

Thanks to the many Perl Mongers who have made us feel athome as we've visited your cities Let's do it again sometime

And finally, our sincerest thanks to our friend Larry Wall, forhaving the wisdom to share his really cool and powerful toyswith the rest of the world so that we can all get our work donejust a little bit faster, easier, and with more fun

Trang 27

Welcome to the next step in your understanding of Perl You'reprobably here either because you want to learn to write

programs that are more than 100 lines long or because yourboss has told you to do so

See, our Learning Perl book was great because it introduced the

use of Perl for short and medium programs (which is most ofthe programming done in Perl, we've observed) But, to avoidhaving "the Llama book" be big and intimidating, we left a lot ofinformation out, deliberately and carefully

In the pages that follow, you can get "the rest of the story" inthe same style as our friendly Llama book It covers what youneed to write programs that are 100 to 10,000 lines long

For example, you'll learn how to work with multiple

programmers on the same project This is great, because unlessyou work 35 hours each day, you'll need some help with largertasks You'll also need to ensure that all your code fits with theother code as you develop it for the final application

This book will also show you how to deal with larger and morecomplex data structures , such as what we might casually call a

"hash of hashes" or an "array of arrays of hashes of arrays."Once you know a little about references, you're on your way toarbitrarily complex data structures

And then there's the buzzworthy notion of object-oriented

programming (OOP), which allows parts of your code (or

hopefully code from others) to be reused with minor or majorvariations within the same program The book will cover that aswell, even if you've never seen objects before

An important aspect of working in teams is having a release

Trang 28

And, just as was promised and delivered in Learning Perl, we'll

entertain you along the way with interesting examples and badpuns (We've sent Fred, Barney, Betty, and Wilma home,

though A new cast of characters will take the starring roles.)

Trang 29

We'll presume that you've already read Learning Perl, or at least

pretend you have, and that you've played enough with Perl toalready have those basics down For example, you won't see anexplanation in this book that shows how to access the elements

Perl operators such as grep, map, sort, and print

File manipulation such as open, file reading, and -X (file

tests)

You might pick up deeper insight into these topics in this book,but we're going to presume you know the basics

Trang 30

Like Learning Perl, this book relegates some of the more

esoteric items out of the way for the first reading and placesthose items in footnotes.[*] You should skip those the first timethrough and pick them up on a rereading You will not find

anything in a footnote that you'll need to understand any of thematerial we present later

[*] Like this.

Trang 31

Hands-on training gets the job done better The best way toprovide this training is with a series of exercises after everyhalf-hour to hour of presentation Of course, if you're a speedreader, the end of the chapter may come a bit sooner than ahalf hour Slow down, take a breather, and do the exercises!

Each exercise has a "minutes to complete" rating We intend forthis rating to hit the midpoint of the bell curve, but don't feelbad if you take significantly longer or shorter Sometimes it'sjust a matter of how many times you've faced similar

programming tasks in your studies or jobs Use the numbersmerely as a guideline

Every exercise has its answer in the Appendix Again, try not topeek; you'll ruin the value of the exercise

Trang 32

If you're a Perl instructor who has decided to use this as yourtextbook, you should know that each set of exercises is shortenough for most students to complete in 45 minutes to an hour,with a little time left over for a break Some chapters' exercisesshould be quicker, and some may take longer That's becauseonce all those little numbers in square brackets were written,

we discovered that we didn't know how to add

So let's get started Class begins after you turn the page

Trang 33

Before we get started on the meat of the book, we want tointroduce some intermediate-level Perl idioms that we use

throughout the book These are the things that typically setapart the beginning and intermediate Perl programmers Alongthe way, we'll also introduce you to the cast of characters thatwe'll use in the examples throughout the book

Trang 35

expression in a scalar context If the expression evaluates to a

true value, grep passes $_ on to the output list

my @lunch_choices = grep &is_edible($_), @gilligans_posessions

In a list context, the grep operator returns a list of all such

selected items In a scalar context, grep returns the number of

Trang 36

which is to say that grep borrows the use of this variable but

Trang 37

fact, we would have been wrong to keep the return because

Trang 38

The map operator has a very similar syntax to the grep operatorand shares a lot of the same operational steps For example, ittemporarily places items from a list into $_ one at a time, andthe syntax allows both the expression block forms

However, the testing expression becomes a mapping

expression The map operator evaluates the expression in a listcontext (not a scalar context like grep) Each evaluation of theexpression gives a portion of the many results The overallresult is the list concatenation of all individual results In ascalar context, map returns the number of elements that arereturned in a list context But map should rarely, if ever, be used

Trang 39

But we're not limited to having only one output for each input.Let's see what happens when each input produces two outputitems:

my @result = map { split //, $_ } @input_numbers;

The inline block of code splits each number into its individualdigits For 1, 2, 4, and 8, we get a single result For 16, 32, and

Trang 40

If a particular invocation results in an empty list, map

concatenates that empty result into the larger list, contributingnothing to the list We can use this feature to select and rejectitems For example, suppose we want only the split digits ofnumbers ending in 4:

Of course, everything we can do with map and grep, we can also

do with explicit foreach loops But then again, we can also code

in assembler or by toggling bits into a front panel.[*] The point isthat proper application of grep and map can help reduce the

level issues rather than details

complexity of the program, allowing us to concentrate on high-[*] If you're old enough to remember those front panels.

Ngày đăng: 26/03/2019, 17:12