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

The Complete Reference Second Edition pot

1,2K 416 0
Tài liệu đã được kiểm tra trùng lặp

Đ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

Tiêu đề Perl: The Complete Reference Second Edition
Tác giả Martin C. Brown
Trường học Osborne/McGraw-Hill
Chuyên ngành Computer Science
Thể loại sách tham khảo
Năm xuất bản 2001
Thành phố New York
Định dạng
Số trang 1.249
Dung lượng 8,21 MB

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

Nội dung

Complete Reference, Perl Programmer’s Reference,ActivePerl Developer’s Guide, and Debugging Perl.. The idea of this book is to provide a reference guide to everything you could possibly

Trang 1

TE AM

Team-Fly®

Trang 2

Second Edition

Trang 4

Perl: The Complete Reference

Trang 5

0-07-219425-1

The material in this eBook also appears in the print version of this title: 0-07-212950-6

All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a marked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringe- ment of the trademark Where such designations appear in this book, they have been printed with initial caps

trade-McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069

TERMS OF USE

This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior con- sent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms

THE WORK IS PROVIDED “AS IS” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES

AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED

TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will

be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error

or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the tent of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even

con-if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause soever whether such claim or cause arises in contract, tort or otherwise.

what-DOI: 10.1036/0072194251

Trang 6

“jjskdjjvoookko000000000000000000000”

Trang 7

Complete Reference, Perl Programmer’s Reference,

ActivePerl Developer’s Guide, and Debugging

Perl In addition to Perl, he has worked in

Python, Java, Visual Basic, and other languages

A programmer for 15 years, he is the former

IT director of a large advertising agency

dealing with blue chip clients such as Hewlett

Packard, Oracle, and Cable & Wireless

Copyright 2001 The McGraw-Hill Companies, Inc Click Here for Terms of Use

Trang 8

Contents at a Glance

Part I Fundamentals

1 Perl Backgrounder 3

2 Perl Overview 17

3 Perl Parsing Rules 37

4 Variables and Data 73

5 Statements and Control Structures 109

6 Subroutines, Packages, and Modules 123

7 Working with Files 161

8 Data Manipulation 209

9 Errors and Trapping Them 269

Part II Programming with Perl 10 Complex Data Structures 287

11 System Information 339

12 Networking 361

vii Copyright 2001 The McGraw-Hill Companies, Inc Click Here for Terms of Use

Trang 9

13 Database Systems 391

14 Interprocess Communication 447

15 Other Execution Enhancements 479

Part III Developing Applications 16 User Interface Tools 513

17 Advanced User Interfaces 529

18 Developing for the World Wide Web (WWW) 575

19 Controlling Execution with Pragmas 611

20 Extending and Embedding Perl 641

Part IV Fine-Tuning Applications 21 Debugging and Tuning 715

22 Perl Compiler 773

23 Perl Documentation 803

24 Cross-Platform Migration Traps 825

25 Distributing Modules and Applications 837

Part V Appendixes A Function Reference 869

B Standard Perl Library 993

C Resources 1141

Index 1153

Trang 10

Acknowledgments xxxiii

Introduction xxxv

Part I Fundamentals 1 Perl Backgrounder 3

Versions and Naming Conventions 5

Perl, perl or PeRl? 5

Life Before Perl 5.6 5

Perl History 6

Main Perl Features 7

Perl Is Free 7

Perl Is Simple to Learn, Concise, and Easy to Read 7

Perl Is Fast 7

Perl Is Extensible 7

Perl Has Flexible Data Types 8

Perl Is Object Oriented 8

Perl Is Collaborative 8

Compiler or Interpreter 8

ix

Copyright 2001 The McGraw-Hill Companies, Inc Click Here for Terms of Use

Trang 11

Similar Programming Languages 9

Unix Shells 9

Tcl 10

Python 10

Java 11

C/C++ 12

awk/gawk 12

Popular “Mythconceptions” 13

It’s Only for the Web 13

It’s Not Maintenance Friendly 13

It’s Only for Hackers 13

It’s a Scripting Language 14

There’s No Support 14

All Perl Programs Are Free 14

There’s No Development Environment 14

Perl Is a GNU Project 15

Perl Is Difficult to Learn 15

Perl Success Stories 15

2 Perl Overview 17

Installing and Using Perl 18

Writing a Perl Script 19

Perl Under Unix 19

Perl Under Windows 22

Perl Under Mac OS 28

Perl Components 32

Variables 32

Operators 34

Statements 34

Subroutines (Functions) 34

Modules 35

Where Next? 35

3 Perl Parsing Rules 37

The Execution Process 38

Syntax and Parsing Rules 39

Basic Syntax 40

Comments 41

Component Identity 43

Operators and Precedence 44

Bare Words 66

Contexts 67

Logical Values 69

Perl Coding Styles 70

x P e r l : T h e C o m p l e t e R e f e r e n c e

Team-Fly®

Trang 12

4 Variables and Data 73

Basic Naming Rules 74

Scalar Variables 75

Literals 76

Numeric Literals 76

String Literals 77

Quotes 80

Interpolation of Array Values 81

Here Documents 82

Arrays 85

Hashes 89

Lists 94

Typeglobs 96

The defined Function and the Undefined Value 97

Default Values 98

Other Tokens 98

Special Variables 98

5 Statements and Control Structures 109

Code Blocks 110

Conditional Statements 111

Loops 114

while Loops 114

until Loops 115

for Loops 115

foreach Loops 116

The continue Block 117

Labels 118

Loop Control 119

Unqualified Blocks 120

goto 122

6 Subroutines, Packages, and Modules 123

Functions 125

Arguments 127

Return Values 137

Error Notification 138

Context 138

Attributes 139

Prototypes 141

Packages 143

Package Symbol Tables 145

Trang 13

Special Blocks 146

Modules 148

Creating Modules 148

The Exporter Module 149

Comparing use and require 150

no 153

do 153

Scope 154

Effects of my 155

Effects of local 156

Effects of our 157

Scope Within Loops 158

Autoloading 158

7 Working with Files 161

Filehandles 163

Opening and Closing Files 164

Reading and Writing Filehandles 172

Locating Your Position Within a File 181

Miscellaneous Control Functions 183

File Management 186

File Information 187

Basic File Management 192

Accessing Directory Entries 196

Managing Directories 198

File Control with fcntl 200

I/O Control with ioctl 203

select 203

File Locking 205

8 Data Manipulation 209

Working with Numbers 210

abs—the Absolute Value 210

int—Converting Floating Points to Integers 211

exp—Raising e to the Power 211

sqrt—the Square Root 211

log—the Logarithm 212

Trigonometric Functions 212

Conversion Between Bases 213

Conversion Between Characters and Numbers 214

Random Numbers 214

Working with Very Small Integers 216

Trang 14

Working with Strings 217

String Concatenation 217

String Length 218

Case Modifications 218

End-of-Line Character Removal 219

String Location 219

Extracting Substrings 220

Stacks 221

Splicing Arrays 223

join 224

split 226

grep 227

map 228

sort 228

reverse 230

Regular Expressions 231

Pattern Modifiers 232

The Match Operator 233

The Substitution Operator 236

Translation 240

Regular Expression Elements 242

Regular Expression Variables 258

Regular Expression Extensions/Assertions 259

Precompiling Expressions 261

Regular Expression Support Functions 263

Unicode 265

Perl’s Interpretation of Unicode 266

Unicode Characters in Perl 266

Unicode’s Effects on Perl Code 267

9 Errors and Trapping Them 269

Adding Error Checking to Your Scripts 270

Error Checking Methods 270

Error Checking Guidelines 272

What to Check 273

What Not to Check 274

When to Stop Checking 275

Don’t Check Things Twice 275

Functions, Return Values, and Nesting 276

Error Messages and Numbers 277

Reporting Errors Within Scripts 279

The Warn Function 279

The Die Function 280

Directives and Tokens 280

Trang 15

Reporting Errors Within Modules 281

The Carp Function 282

The Cluck Function 283

The Croak Function 283

The Confess Function 283

Part II Programming with Perl 10 Complex Data Structures 287

Accessing Packed Data Structures 288

References 293

Creating Hard References 294

Dereferencing 298

Determining a Reference Type 301

Symbolic References 302

Complex Structures 303

Arrays of Arrays 304

Hashes of Hashes 309

Arrays of Hashes 313

Hashes of Arrays 315

Beyond Two Dimensions 317

Objects 321

Object Basics 321

Creating and Using Objects 322

Methods 325

Classes and Inheritance 329

Destructors and Garbage Collection 330

Comparing Perl Objects to Other Languages 330

Using tie 331

Creating New tie Classes 332

11 System Information 339

Users and Groups 340

Getting Unix Password Entries 341

Getting Unix Group Entries 343

Password Encryption 344

Time 345

gmtime and localtime 345

time Function 347

Comparing Time Values 347

Converting Dates and Times into Epochs 348

Trang 16

Time Arithmetic 348

times Function 351

sleep Function 352

Alarms 353

Environment Variables 353

12 Networking 361

Obtaining Network Information 364

Hosts 364

Protocols 366

Services 367

Networks 368

The Socket Module 368

Address Resolution and Conversion 369

Address Constants 369

Socket Structures 370

Line Termination Constants 370

Socket Communication 371

Connecting to a Remote Socket 371

Listening for Socket Connections 374

Using IO::Socket 380

Client Side 381

Server Side 381

Using IO::Socket and IO::Select 382

Getting Socket Addresses 383

Closing Sockets 384

Socket Options 384

Data Transfer 386

Graham Barr’s libnet Bundle 387

Gisle Aas’ LWP Bundle 389

13 Database Systems 391

Text Databases 393

Delimited Databases 395

Fixed-Length Records 395

DBM Databases 399

DBM Implementations 400

DBM Functions 402

Using Tied DBM Databases 403

Converting Between DBM Formats 406

Using AnyDBM_File 407

GDBM Features 408

Trang 17

Berkeley DB Features 409

Storing Complex Data in a DBM Database 418

Relational Databases with DBM 421

Database File Locking 424

Using the DBI and Win32::ODBC Toolkits 425

DBI 425

Win32::ODBC 426

Database Mechanics and Compatibility 427

Connecting to a Database 428

Executing Simple Queries 430

Executing Extended Queries 431

Closing the Connection 432

Identifying Errors 433

Doing More 433

SQL Refresher 434

SQL Statements 435

14 Interprocess Communication 447

Processes 448

Controlling Perl Execution 449

Process Information 449

Process Groups 449

Process Priority 450

Signals 451

Signal Handlers 453

The WARN and DIE Signals 455

Sending Signals 458

Pipes 459

Anonymous Pipes 459

Two-Way Communication 460

Named Pipes 461

Named Pipes Under Windows 463

Safe Pipes 467

Executing Additional Processes 468

Running Other Programs 468

Replacing the Current Script 470

Creating Child Processes 470

Other Function Calls 477

System V IPC 478

15 Other Execution Enhancements 479

Perl on the Command Line 480

Special Handling 489

Trang 18

Perl Environment Variables 489

Perl in Perl (eval) 491

Using eval EXPR 492

Using eval BLOCK 492

Trapping Exceptions 493

Returning Information 493

eval and the DIE signal handler 494

Threads 494

How Multitasking Works 494

From Multitasking to Multithreading 495

Comparing Threads to Multiple Processes 497

Comparing Threads to select() 498

Threads and Perl 498

Creating a New Thread 498

Creating a Thread Using an Anonymous Subroutine 499

Controlling a Thread 500

Controlling Variables 501

Controlling Subroutines 502

Queues 503

Semaphores 504

Signals 504

Security 505

Using Taint Mode 505

The Safe and Opcode Modules 508

Part III Developing Applications 16 User Interface Tools 513

Processing Command Line Arguments 514

Getopt::Std 515

Getopt::Long 516

Perl’s Reporting Mechanism 521

Headers and Footers 525

Format Functions 526

Format Variables 527

17 Advanced User Interfaces 529

Working with a Terminal 531

Using Tk 532

Installing Tk Under Unix 533

Installing Tk Under Windows 533

Hello from Tk 533

Trang 19

Event Loops 537

Widgets 540

Controlling Window Geometry 563

Easing the Process 567

18 Developing for the World Wide Web (WWW) 575

HTML 576

Uniform Resource Locators 578

Web Operation Overview 579

The Environment 580

The Common Gateway Interface 584

Extracting Form Data 586

Sending Information Back to the Browser 589

Document Body 593

Smarter Web Programming 593

The CGI Module 594

Cookies 598

Parsing HTML 601

Parsing XML 602

Debugging and Testing CGI Applications 605

Security 608

19 Controlling Execution with Pragmas 611

Warnings 612

The $^W Variable 614

The Old warnings Pragma 614

Lexical Warnings in Perl 5.6 615

The strict Pragma 620

The vars Option 621

The refs Option 623

The subs Option 624

Other Perl Pragmas 625

attributes 625

autouse 626

base 627

blib 628

bytes 628

charnames 629

constant 629

diagnostics 631

fields 633

Trang 20

filetest 634

integer 634

less 634

lib 635

locale 636

open 636

ops 636

overload 637

re 637

sigtrap 638

subs 639

vars 640

20 Extending and Embedding Perl 641

Perl Internals 643

Architecture 644

Internal Objects 644

Translator 646

Opcodes 647

Compilation 650

Execution 652

Perl’s Internal Structures 653

Variables 654

The Stack 662

Stack Size 668

Internals Summary 669

Extending Perl 669

The Extension Interface 670

XS Overview 670

SWIG Overview 671

Using XS 672

Embedding Perl 698

Embedding the Perl Interpreter 699

Using a Specific Perl Function 700

Multiplicity 704

XS Initialization 705

Cooperating with Other Languages 706

Converting Other Languages to Perl 706

Converting Perl to Other Languages 711

Calling Other Languages from Perl 712

Trang 21

Part IV Fine-Tuning Applications

21 Debugging and Tuning 715

Debugging Techniques 717

Using print 717

Using caller 721

Using eval 724

Writing a Log 726

Reporting to syslog 729

Reporting to the Windows NT/2000 Event Log 729

Using a Debugger 730

Watches 730

Stepping 730

Breakpoints 731

The Perl Debugger 731

The ActivePerl Debugger 748

Traps for Programmers of Other Languages 750

Differences from awk/gawk 750

C Traps 752

sed Traps 754

emacs Traps 754

Shell Script Traps 754

Python Traps 755

Optimization 757

The Perl Profiler 758

Profiling by Hand 765

Optimization Guide 766

22 Perl Compiler 773

Using dump 775

Using the Compiler 776

The Backends 777

The perlcc Frontend 791

Differences Between Interpreted and Compiled Code 795

Comparing Script and Executable Speeds 795

Tests 797

Summary Results 800

23 Perl Documentation 803

Using the Supplied Documentation 805

Unix 808

Windows 810

Mac OS/Mac OS X 811

xx P e r l : T h e C o m p l e t e R e f e r e n c e

Team-Fly®

Trang 22

Writing POD Documentation 812

POD Components 813Command Paragraph 813Ordinary Text Paragraph 816Verbatim Paragraph 816Escape Sequences 816Embedding Documentation 816Converting POD to Other Formats 818

Text 819HTML 820Unix man Pages 820PostScript/PDF 823Converting POD to HTML On The Fly 823

24 Cross-Platform Migration Traps 825

Performance and Resources 830

Platform Migration Tricks 831

Determining Your Platform 831Determining the Perl Version 832Checking for Supported Functions 833Function Overloading 834

25 Distributing Modules and Applications 837

Perl Makefiles and ExtUtils::MakeMaker 838

Perl Makefiles and CPAN 839Perl Makefiles and PPM 839Extension Building and Installation Overview 840MakeMaker Overview 842Start with h2xs 843MakeMaker Configurable Options 845Creating a Dummy Makefile 853Default Makefile Targets 853Creating a New Perl Binary 854Targets for Package Builders 855Related Modules 858

Trang 23

MakeMaker Tricks 860

Checking for Prerequisites 860Packing for CPAN 863Packing for PPM/VPM 863

Part VAppendixes

A Function Reference 869

-X 879abs 880accept 881alarm 881atan2 882bind 882binmode 883bless 883caller 884chdir 884chmod 885chomp 885chop 886chown 886chr 887chroot 887close 888closedir 888connect 889continue 889cos 890crypt 890dbmclose 890dbmopen 891defined 892delete 892die 893

do 893dump 894each 895endgrent 895endhostent 895endnetent 896endprotoent 896

Trang 25

grep 920hex 920import 921index 921int 922ioctl 922join 922keys 923kill 923last 925

lc 925lcfirst 925length 926link 926listen 927local 927localtime 928log 928lstat 929m// 929map 929mkdir 930msgctl 930msgget 931msgrcv 931msgsnd 932

my 932next 933

no 933oct 934open 934opendir 937ord 937our 937pack 938package 940pipe 940pop 941pos 941print 942printf 942prototype 945push 945

Trang 27

sin 967sleep 968socket 968socketpair 969sort 969splice 970split 970sprintf 971sqrt 972srand 972stat 972study 974sub 974substr 975symlink 975syscall 976sysopen 976sysread 978sysseek 978system 979syswrite 980tell 980telldir 981tie 981tied 982time 982times 982tr/// 983truncate 983

uc 984ucfirst 984umask 984undef 985unlink 985unpack 986unshift 986untie 986use 987utime 988values 988vec 988wait 989waitpid 989

Trang 28

Using Scalar Elements 1008

Using Array Elements 1008

Using Hash Elements 1009

Using Class Elements 1010

Trang 29

Data::Dumper 1017DB_File 1018Devel::SelfStubber 1020DirHandle 1020DynaLoader 1021English 1021Env 1024Errno 1025Exporter 1025

Unknown Symbols 1026Tag-Handling Functions 1026Version Checking 1027ExtUtils::Command 1027ExtUtils::Embed 1028ExtUtils::Install 1029ExtUtils::Installed 1029ExtUtils::Liblist 1029ExtUtils::MakeMaker 1030ExtUtils::Manifest 1030ExtUtils::Miniperl 1030ExtUtils::Mkbootstrap 1030ExtUtils::Mksymlists 1030ExtUtils::MM_OS2 1030ExtUtils::MM_Unix 1030ExtUtils::MM_VMS 1031ExtUtils::MM_Win32 1031ExtUtils::Packlist 1031Fatal 1031Fcntl 1031FileCache 1032FileHandle 1033File::Basename 1035File::CheckTree 1036File::Compare 1037File::Copy 1037File::DosGlob 1038File::Find 1039File::Path 1040File::Spec 1041File::Spec::Mac 1042File::Spec::OS2 1043File::Spec::Unix 1043File::Spec::VMS 1045

Trang 31

Safe 1111SDBM_File 1114Search::Dict 1114SelectSaver 1114SelfLoader 1115Shell 1116Socket 1116Symbol 1118Sys::Hostname 1119Sys::Syslog 1119Term::Cap 1121Term::Complete 1122Term::ReadLine 1123Test 1124Test::Harness 1127Text::Abbrev 1127Text::ParseWords 1128Text::Soundex 1129Text::Tabs 1130Text::Wrap 1131Tie::Array 1131Tie::Handle 1132Tie::Hash 1132Tie::RefHash 1133Tie::Scalar 1133Tie::SubstrHash 1134Time::Local 1134Time::gmtime 1135Time::localtime 1136Time::tm 1137UNIVERSAL 1137User::grent 1138User::pwent 1139utf8 1139

C Resources 1141

Supplied Documentation 1142

Unix Documentation 1142Windows Documentation 1143Mac OS Documentation 1143Other Platforms 1144Books 1144

xxx P e r l : T h e C o m p l e t e R e f e r e n c e

Team-Fly®

Trang 32

General Mailing Lists 1149

Windows-Specific Mailing Lists 1149

Newsgroups 1150

Index 1153

Trang 34

First of all, I’d like to thank my wife Two years ago, based on the offer for the first

edition of Perl: The Complete Reference, she stood by me when I wanted to start

writing full time Without her continued support, I wouldn’t have written the firstedition or the various other books that I’ve written since then, or been able to do thissecond edition Meanwhile, she still gives advice, listens to my rants when things aren’tgoing well, and continues to be impressed when each book arrives

Next, I’d like to thank all the people at Osborne who made this book possible Thatincludes Wendy Rinaldi for offering me the opportunity, Rebekah Young for keeping

me in check, LeeAnn Pickrell and Betsy Manini for getting it through production, thedesktop compositors for laying out each chapter, and Andy Carroll and Bob Campbellfor doing the copy editing

For technical input, thanks again to Mark Strivens, Ann-Marie Mallon, Huga vander Sanden, Jon Nangle, and a myriad of others, including those people on Cix whogave me ideas and input about topics and tricks that should be included in the book.It’s not possible to write a Perl book without thanking Perl’s original author and thecurrent maintainers—that includes Larry Wall, Tom Christiansen, Randal L Schwartz,Sriram Srinivasan, Gurusamy Sarathay, and many many others It continues to amaze

me how much you can cram into one language, and these people are the ones who do it

If there’s anybody I’ve forgotten to acknowledge, I apologize unreservedly inadvance I have done my best to check and verify all sources and contact all partiesinvolved, but it’s perfectly possible I made a mistake

xxxiiiCopyright 2001 The McGraw-Hill Companies, Inc Click Here for Terms of Use

Trang 36

The idea of this book is to provide a reference guide to everything you could

possibly want to know about Perl I’ve done my best to try and cover all thedifferent aspects, from the core of the language to the different functions, and

on into the different tasks and areas of the Perl language I even cover how to debugyour software, write documentation, and then build and distribute your applications

or modules to the world at large Along the way, we also look at some nonstandardfeatures and extensions, including better ways of networking, web programming, anddesigning interfaces

Throughout the entire book, you’ll find real-world examples and guides on how toapproach real problems using Perl—not just how to use the features of Perl If all youwant is a quick reference guide to the different areas of Perl, then use the appendixes

at the end of the book and on the Web at www.osborne.com, which cover basic

components, functions, the Perl standard library, CPAN (Comprehensive Perl ArchiveNetwork) extension library, a complete guide to errors and warnings, and a list ofresources for more information

xxxvCopyright 2001 The McGraw-Hill Companies, Inc Click Here for Terms of Use

Trang 37

What’s Changed Since the First Edition?

Beyond the obvious updates and fixes for the newer versions of Perl, we’ve also

changed the overall layout of this edition We got a lot of feedback on the first editionand its pitfalls and problems The most requested feature was a better introductoryguide to the language As such, we’ve completely restructured the first section

of the book to provide a well-rounded introduction to the language, for people new

to programming and for those migrating from another language

The second and third sections have been updated, with many of the chaptersmodified to provide a more solution-oriented approach, and that means the order andcontent of many of the chapters has been changed We’ve expanded on the content inmany areas, including more information on networking, database access (which now

covers the DBI extension and Win32::ODBC module) and web programming.

The last section has also been modified into a guide for the final processes behindturning your Perl program into a distributable application This includes debuggingand retuning your script and using the Perl compiler to improve performance andfind coding errors The chapter on Perl documentation has also been updated to

provide information on using the supplied documentation and information on how

to write your own Finally, we cover the topics of cross-platform development andthe packaging and distribution of your application or module

Overall, I’ve tried to make the book less Unix-centric and cover more of the issuessurrounding cross-platform development throughout the book, instead of concentratingthe information into a few chapters at the end

Who Is the Book For?

I haven’t targeted the book at any specific group of Perl users To put it simply, if youprogram in Perl, you will find this book useful As a reference, most people should find

it useful to keep on the desk or the shelf just as a quick means of looking up a particularfunction or feature For learners and expert users alike, the information in this bookwill be invaluable

You should also find the book useful if you want to know how to do a particulartask in Perl, since you’ll also find working real-world examples of the different features

of Perl within the book If you are looking for more examples, you might want to look

at Perl Annotated Archives, which contains over 100 scripts to solve a myriad of different

problems For more information on migrating Unix scripts to the Windows platform,

especially when using the ActivePerl distribution, try ActivePerl Developer’s Guide.

If debugging and tuning are more your thing, then look at Debugging Perl You can

get more information on all of these titles and many others, in Appendix C

Trang 38

How to Use This Book

Pick it up, look up the feature you want to get more information on from the contents

or the index, and read! The scripts and script fragments included in the book should all

work without modification on your machine Be aware though that not all platforms

support all Perl features—Chapter 24 provides a guide to most of the issues

surrounding cross-platform development

If you want purely reference information—that is, you want to look up the

arguments and return values to a function—then use the appendixes at the back of the

book and on the Web at www.osborne.com For discussion, examples, and detailed

information on a particular feature, use one of the earlier chapters You should find

references between the chapters and appendixes in both directions to help you get

more information

Chapter Breakdown

Each chapter in the book attempts to cover a different aspect of the solutions that Perl

is able to provide

will need to use and understand in order to make the best use of Perl

installing Perl onto your machine (Unix, Windows, and Mac OS are covered), to

writing and executing your first script We also look at some of the key terms that

you come across while reading the book and using Perl

language, including an outline of how the execution process works, and all of the

different components that make up a Perl script

scalar, the array and the hash (or associative array)

and execution of your program

different components, from simple subroutines, right up to the more complex issues

of creating your own modules

screen to reading information from multiple files

and popular use of Perl We start by looking at basic ways of manipulating strings and

arrays before covering the Perl regular expression mechanism

and bugs, and how to go about handling the situation without upsetting the user

Trang 39

Chapter 10looks at the more complex data structures available in Perl—arrays andhashes We go beyond the normal uses of these structures and look at other ways theycan be employed to aid in the programming process We also take the opportunity toexamine references, which provide a different way of accessing and using informationstored in variables, and this leads us on to nested data structures and object-orientedprogramming This final section also leads to tied data structures—a system wherebyinformation from an external source can be attached to an internal data structure.

information about users and groups, time and how to manipulate time values, andfinally the environment and how it can affect the execution of your script

over standard network sockets, such as those used for communication over the Internet

homegrown and using systems such as DBM, Oracle, and ODBC sources

both standard filehandles and System V IPC functions The chapter also describes themethods available for creating, controlling, and communicating with external processes

supplying arguments to the command line, to executing scripts within scripts (using

eval), to multi-threaded execution

information back to your users through a structured interface on the command lineand back through the Perl reporting mechanism

interface to the Tk user interface development system

web scripts This covers the physical environment of a script and also the ways of

communicating between the web server, the user’s browser, and a Perl script, otherwiseknown as CGI We then go on to look at smarter ways of handling the web-developmentprocess and the specifics of web programming with Perl, including a useful checklist ofthe security issues surrounding the web-programming process

Perl uses a series of pragmas to improve the monitoring of potential problems in yourscript, provide additional warnings and error messages, and change the way in whichdifferent aspects of your scrip are interpreted

and libraries or through embedding Perl into your existing applications

level and at deeper levels within the Perl interpreter We also look at how to debugregular expressions and how to use the Perl profiler to determine which parts of yourPerl script need optimization

systems that take a Perl script and produce a number of different reports and outputformats At a simple level, this includes a parsing tree that describes the real execution

Trang 40

profile of your script, and at the other end of the scale, the compiler that supports the

creation of stand-alone Perl binaries

reading supplied documentation and writing your own

cross-platform compatible, even if you don’t know what the destination platform is

We look at the basics of using Perl in different environments, the major differences and

things to watch out for, and also ways in which you can make a script more aware of

its surroundings

community In particular, it describes the MakeMaker utility for creating Perl Makefiles

that can compile and automatically install Perl extensions

The appendixes at the back of the book provide a quick reference resource for Perl

functions (Appendix A) and the standard Perl library (Appendix B) Appendix C gives

a list of all of the different areas—books, websites, mailing lists, and newsgroups—that

can provide more information on how to use and program with Perl

The appendixes on the Web (www.osborne.com) provide a reference to the core

Perl constructs (Web Appendix A), the extensions for Perl available from CPAN

(Web Appendix B), and a complete list and description of all the warnings and error

messages generated by the Perl interpreter (Web Appendix C).

Conventions Used in This Book

All Perl keywords are highlighted in bold, but functions are listed without parentheses.

This is because the C functions on which the Perl versions may be based are shown

like this( ).

Examples and code are displayed using a fixed-width font

Function descriptions are formatted using the same fixed-width font

Notes are formatted like this and include additional information about a particular

topic You’ll also find similarly formatted “Cautions” and “Warnings,” which highlight

possible dangerous tools or tricks to watch out for when programming.

Contacting the Author

I always welcome comments and suggestions on my work I particularly appreciate

guides and recommendations on better ways of achieving different goals, especially

with a language as varied and capable as Perl The best way to contact me is via

email You can use either books@mcwords.com Alternatively, visit my website,

the scripts and contents of this book You can find the homepage for this book at

Ngày đăng: 18/03/2014, 00:20

TỪ KHÓA LIÊN QUAN