It's also possible to create really stunning Perl programs with just a small bit ofcode.. Using a little bit of Perl to glue together other applications, languages, andtechnologies, you'
Trang 1SAMS Teach Yourself Perl in 24 Hours THIRD EDITION
By Clinton Pierce
Publisher: Sams Publishing Pub Date: June 15, 2005 ISBN: 0-672-32793-7 Pages: 480
Table of Contents | Index
Learn Perl programming quickly and easily with 24 one-hour lessons in Sams Teach Yourself Perl in 24 Hours, 3/e These step-by-step lessons will teach you the basics of
Perl and how to apply it in web development and system administration Plus, the third edition has been updated to include 5 chapters on new technologies, information
on the latest version of Perl and a look ahead to Perl 6 You will focus on real-world development, including how to:
Trang 2SAMS Teach Yourself Perl in 24 Hours THIRD EDITION
By Clinton Pierce
Publisher: Sams Publishing Pub Date: June 15, 2005 ISBN: 0-672-32793-7 Pages: 480
Trang 7Installing the Modules Under…
What to Do When You're Not Allowed to Install Modules Index
Trang 8Copyright © 2005 by Sams Publishing
All rights reserved No part of this book shall be reproduced, stored in a retrievalsystem, 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 containedherein Although every precaution has been taken in the preparation of this book,the publisher and author assume no responsibility for errors or omissions Nor isany liability assumed for damages resulting from the use of the informationcontained herein
as affecting the validity of any trademark or service mark
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied The information provided is on an
"as is" basis The author and the publisher shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising
Trang 9Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered inquantity for bulk purchases or special sales For more information, pleasecontact
Trang 11Clinton Pierce is a software engineer, freelance programmer, and instructor He
has been answering questions about Perl on USENET for many years and hasbeen writing courseware and teaching Perl to his co-workers and anyone elsewho will listen for about as long He is a software engineer for a payroll
company, who, when not designing middleware software to integrate legacysystems to the Web, navigating the intricacies of payroll taxes, teaching UNIXand Perl, writing books and articles, or writing programs at home Just For TheFun Of It, harbors secret dreams of being abducted by wood nymphs and living
in the deep forest without technology You can visit his Web site at
http://www.geeksalad.org for updates and corrections, or just to say hello
Trang 12"If I have seen further, it is by standing on the shoulders of Giants" Isaac
Newton
Any book on Perl should first recognize the Giant who gave us Perl in the firstplace Thanks, Larry
I not only stood on the shoulders of Giants, but also was led by hoards of others
To make sure this book came out as error-free as possible, I invited perfect
strangers to watch, criticize, and correct me when necessary This has been ahumbling experience In no particular order, the people who annoyed me themost and who deserve the most thanks are Abigail, Greg Bacon, Sean Burke,Ken Fox, Kevin Meltzer, Tom Phoenix, and Randal Schwartz Also, thanks toMichael Schwern, Tom Grydeland, Matt Bielanski, Mark Jason-Dominus, JeffPinyan, Gary Ross, Andrew Chen, and John Bell for finding bugs and offeringsuggestions Over the years helpful readers have been instrumental in weedingout small problems with the text and helping with the explanations, notably: Lisa
M, Robert B, Qinglin L, Ihor P, David K, Dan G, and Laura C
Some small credit should also go to #perl for letting me sound my ideas off themand for giving me their honestand sometimes brutalopinions
Somewhat responsible for this book are Bill Crawford and Donna Hinkle forgetting me into this whole training mess in the first place Thanks, I think
Of course, I'd like to thank the people at Sams Publishing who put up with a newauthor and all the pain and agony that goes with the territory Without peoplelike Randi Roger, Scott Meyers, Kate Givens, and everyone behind the scenesthat I didn't get to talk to but who are just as important, I'd never have put
together anything like this
Trang 13As the reader of this book, you are our most important critic and commentator.
We value your opinion and want to know what we're doing right, what we could
do better, what areas you'd like to see us publish in, and any other words ofwisdom you're willing to pass our way
You can email or write me directly to let me know what you did or didn't likeabout this bookas well as what we can do to make our books stronger
Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able
to reply to every message.
When you write, please be sure to include this book's title and author as well asyour name and phone or email address I will carefully review your commentsand share them with the author and editors who worked on the book
E-mail: opensource@samspublishing.com
Associate Publisher Sams Publishing
800 East 96th Street Indianapolis, IN 46240 USA
Trang 14For more information about this book or another Sams title, visit our website at
www.samspublishing.com Type the ISBN (excluding hyphens) or the title of abook in the Search field to find the page you're looking for
Trang 15"Any sufficiently advanced technology is virtually indistinguishable frommagic."
Arthur C Clarke
Remember this well: There's nothing magical about programming a computer.
Like anything that seems magical, there's always a trick to itand programming is
no different All you need are some analytical thinking skills, the desire to learn,and some time to learn Perl The best way to learn how to program a computerorany task reallyis to have a goal Your goal could be to spice up your Web pages,convert a program you already have to Perl, or to satisfy idle curiosityit doesn'treally matter
Now, given that you've established a goal and have some thinking skills, whatdoes this book have for you?
This book will teach you the basics of the Perl programming language You'lllearn just enough Perl to do something useful You will not be overwhelmed withdetails that, although interesting, will only get in your way and that you'll
probably never use again Each new concept in this book is demonstrated by lots
of working code examples Go aheadflip through the book and see
But why Perl? Almost every company that uses programming of some kind usesPerl Perl is found in finance, manufacturing, genetics, the military, and everyother application known to humankind And, of course, Perl is used on the
Internet and the World Wide Web Perl isn't going away any time soon, which iswhy learning it is an investment in your time that will pay off for years to come
It's also possible to create really stunning Perl programs with just a small bit ofcode Using a little bit of Perl to glue together other applications, languages, andtechnologies, you'll be creating useful Perl programs in no time
Trang 16This book is divided into 24 segments that take roughly an hour to complete.You can work through the lessons in the space of a day (if you don't plan to eat
or sleep), or you can take your time and work through the hour lessons at yourown pace
At the end of each hour, you'll be able to accomplish a new set of tasks Thelessons contain clear explanations of the language features and how they work
In addition, each hour provides you with the opportunity for hands-on training,simply by following the steps described
Trang 18New terms are emphasized by being placed in bold for your easy reference.
Trang 20Perl is used in so many places because Perl is a glue language A glue language
is used to bind things together You probably wouldn't want to write a wordprocessor in Perlalthough you couldbecause good word processors are alreadyavailable Writing a database, a spreadsheet, an operating system, or a full-
featured Web server in Perl would be sillybut again, possible
What Perl is good at is tying these elements together Perl can take your
database, convert it into a spreadsheet-ready file, and, during the processing, fixthe data if you want Perl can also take your word processing documents andconvert them to HTML for display on the Web
As a side effect of being a language designed to glue elements together, Perl isvery adaptable It runs under, at last count, about two dozen operating
systemsand probably more Perl's programming style is very flexible, so you can
do the same things in many ways Your Perl programs may look nothing likemine, but if they both work, that's okay Perl can be a strict language when itneeds to be, but it can also be forgiving to new sprogrammers if you want It's all
up to you
Trang 21Perl The name of the program that runs your programs, the interpreter, is perl.
The distinction usually isn't very important to youexcept when you're trying to
start your programs; then it's always perl Sometimesbut not hereyou will see Perl written as PERL, probably because one explanation of Perl's name is as an acronym for Practical Extraction and Report Language Nobody ever really
called it PERL; it's too pretentious It's just Perl to its friends
By the Way
Many of Perl's features were "borrowed" from other languages Thisborrowing gave rise, early on, to Perl's other acronym-expansion:
Pathologically Eclectic Rubbish Lister.
Trang 22To play with Perl, you first have to install it Perl's installation is designed to beeasy and error free In fact, as part of the installation steps, Perl should do a self-test to make sure that it's okay The installation procedures vary widely
depending on what operating system you have So, to get things moving, pickwhich operating system you have from the sections here, and follow along
Stop! Wait! Maybe You Already Have Perl
Before you go through all the trouble to install Perl on your system, you shouldcheck to see whether you already have it Some Unix vendors ship Perl with theoperating system Windows NT comes with Perl as part of the Windows NTResource Kit (but that version is a bit old) To see whether you have Perl
properly installed on your operating system, you need to get to a commandprompt
Under Unix, simply log in to the system If you have a graphical environment,you need to open a terminal window After you've logged in or opened yourwindow, you may see a prompt like this:
Trang 23Either the system responds with an error message such as command notfound, or Perl responds and prints its version number If Perl prints its versionnumber, it's installed You probably do not have to reinstall it
To see whether Perl is properly installed on a Windows machine you need to get
to an MS-DOS prompt, similar to Figure 1.1
Figure 1.1 You can check your version of Perl at this DOS prompt.
[View full size image]
Trang 24C:\> perl -v
If Perl is properly installed, it answers with its version number As noted in theprevious caution, it should be at least version 5 If MS-DOS replies with Badcommand or file name, you need to install Perl properly
On the Macintosh (running MacOS), you can check to see whether Perl is
installed by running File Find (Command-f) for 'MacPerl' as shown in Figure1.2 If the application is found, open it and look at the "About MacPerl" optionunder the Apple menu You should have at least Version 5.2.0 Patchlevel 5.004;otherwise, you should install a new version of MacPerl
Trang 25Newer Macintosh systems run Mac OS X Underneath the point-and-click
interface, there is a Unix operating system To get a shell prompt (so that you canfollow the Unix instructions) go to Finder, Applications, Utilities and selectTerminal You should see a window similar to Figure 1.3
Figure 1.3 Mac OS X Terminal, with Perl version output.
Generally for Mac OS X, follow the Unix instructions in this book There areextensions particular to Mac OS X that you can download from CPAN
Trang 26To install Perl under Windows, keep in mind that, as with many things in life,you can take the Easy Way or the Hard Way If you're proficient with a C
compiler and the tools needed in a development environmentmakefiles, shells,and so onyou can take the Hard Way and build your own Perl from scratch Thesource to the perl interpreter is free for you to look at, modify, and change tosuit your needs; see Hour 16, "The Perl Community," for details Building Perlfrom scratch under Windows is not easy and probably more hassle than it's worthfor most people
Installing Perl the Easy Way really is easy ActiveState Tool Corp provides aself-installing Perl distribution, and installation works as it does for any otherWindows application, as shown in Figure 1.4 This Perl is distributed under theActiveState Community License, which you should read The URL is
http://www.ActiveState.com
Figure 1.4 Installing Perl under Windows with ActiveState.
Trang 27ActiveState has simply done the hard parts for you and wrapped it up with aninstallation program ActiveState also offers commercial support for Perl, if yourequire it, and offers add-on products such as debuggers and other developmenttools and libraries
Did you Know?
You can go to ActiveState's Web site to get the latest version of Perl
Installing Perl on Unix
To install Perl on Unix, you need a couple of things First, you need a copy ofthe Perl source bundle You can always download the latest bundle from theDownloads area of http://www.perl.com You can find multiple versions there,but the one you want is always labeled "Stable" or "Production." You also need
an ANSI C compiler Don't worry if you don't know what that means Perl'sconfiguration program checks for one, and if the compiler is not there, you caninstall a prebuilt version
After you have the Perl source bundlewhich comes in a file named somethinglike stable.tar.gzthen you need to unpack and install it To do so, enter thesecommands:
Trang 28Building Perl takes quite a while Get some coffee If you have a slow system,get lunch When the build is complete, type two more commands:
$ make test
# make install
Trang 29When make install is correct, you can test Perl's installation by typing thefollowing at the prompt again:
Trang 30http://www.perl.com/CPAN/ports/mac and download the installation file fromthere You should download the most recent version of MacPerl appl.bin fromthat directory Install it by using StuffIt Expander to extract the MacPerl
installation program from the downloaded file, and then running the installationprogram
When you're finished, you will want to set up a helper for the Perl
documentation reader, Shuck, which was installed with MacPerl MacOS 8 userscan do this in the Internet Control Panel by selecting File Mapping from theAdvanced menu and adding a file extension mapping for pod to the Shuckapplication This will give you easier access to the documentation You mightalso want to set up mappings for ph, pl, plx, pm, cgi, and xs (allextensions used by Perl) to the MacPerl application Be sure to set the file type
to 'TEXT'
MacOS 7 users will have to use the InternetConfig utility to perform similarmappings In the InternetConfig, select Helpers, and add a new helper
application shuck for pod Also add helpers for the other extensions
mentioned previously to the MacPerl application
Trang 31:
Trang 32In this case, the entry for the FAQ questions "Who supports Perl? Whodevelops it? Why is it free?" is displayed
Some Special Documentation Cases
When Perl is installed on a Unix system, the installer is given the option to
install manual pages in traditional "man" format If the installer chooses yes, thestandard Perl documentation is converted into man format and stored in an
appropriate place To access the Perl documentation, you can use either the
perldoc program or the man program as you normally would with Unix:
Trang 33When ActiveState's Perl distribution is installed on a Microsoft Windows
system, the manual pages are converted to HTML format and can be accessedwith a Web browser If you want to read the manuals, point your frame-capableWeb browser to the local directory C:\Perl\html if you used the standardinstallation directory; if you didn't, use your selected directory instead
For the Macintosh (not Mac OS X), MacPerl comes with a utility called Shuck
that is located in the MacPerl folder You can use it to read and search the Perldocumentation as shown in Figure 1.5
Figure 1.5 The MacPerl Shuck documentation reader.
What If You Can't Find the Documentation?
Trang 34a directory that's not in your shell's search path Or perhaps your search path isoverly restrictive Hunt around for the perldoc utility, and add that directory
to your shell's PATH environment variable
The second reason is the documentation was removed, either by accident ormalice Perl's installation includes documentation You can't install Perl without
it If the documentation isn't there, a good argument can be made that Perl wasn'tproperly installed or that it has since been corrupted Perhaps youor the systemadministratorshould consider reinstalling Perl The documentation is an integralpart of the Perl development environment, and without it some pieces of Perlwill not function
If all else fails, and you can't get a local copy of the documentation, you can fallback to the Web On Perl's primary distribution site (http://www.perl.com), youcan access the standard set of documentation Having the actual documentationthat came with your version of Perl would be betterit's tailor-made to your
particular version and installationbut this online documentation will do in a
pinch
Trang 35To write your Perl programs, you need a utility called a text editor A text editor
is a program that allows you to enter plain text, without any formatting, into afile Microsoft Windows Notepad and the MS-DOS EDIT.EXE program are bothexamples of text editors For Unix, vi, Emacs, and pico are all text editors Atleast one of them will be available on your system
Under the Mac, the MacPerl application contains a rudimentary text editor; toopen a new program, select New under the File menu For Mac OS X use theTextEdit program This is located in the Finder under Applications Be sure toset the preferences to "plain text" or select "Make Plain Text" under the Formatmenu
You should not use a word processor to type in your Perl programs Word
processorssuch as Microsoft Word, WordPad, WordPerfect, and so onembedformatting codes by default when they save documents, even if the documentscontain no boldface, italic, font changes, or other special formatting These
formatting codes will confuse Perl, and your programs will not work correctly Ifyou need to use a word processor, be sure to save your programs as plain text
Typing Your First Program
Open your text editor, and type the following Perl program exactly as shown:
#!/usr/bin/perl
print "Hello, World!\n";
Trang 36After you type this program into your text editor, save it in a file named hello.You don't need an extension on the filename, but Perl permits you to put onethere Some Windows and Macintosh utilities use extensions to tell what kind offile this is If you need or want to use an extension, pl or plx is common;for example, you can use hello.pl
Trang 37To run the program, for now, you need to get to a command prompt In Unix,open a terminal window or log in On a Microsoft Windows machine, open anMS-DOS prompt Under Mac OS X, use the Finder, select Applications, Utilitiesand run Terminal You should also change into the directory where you storedthe hello program by using your shell's cd command
When you're at the prompt, type the following (A DOS prompt is shown here;Unix has a slightly different prompt.)
C:\PROGRAMS> perl hello
If all goes well, Perl should respond with the following message:
Hello, World!
If typing this command worked, congratulations! Remember how you ran thisprogram because this is how you will start your programs for the rest of thebook (You can use some other ways, which will be covered shortly.)
If it did not work, check for the following:
If you receive the error message Bad command or file name or
perl: command not found, the Perl program is not in your
execution path You need to figure out where the Perl program is installedand add that directory to the PATH variable in your shell
If you receive the error message Can't open perl script
Trang 38probably not in the same directory as the file named hello that you savedearlier, or you saved the file under a different name To change into theproper directory under Unix or Windows, use the cd command For
to the saved file The cat command (Unix) or the type command (DOS)can be used to verify what is in the file If you mistyped, check everything;the quotation marks and punctuation are important
If you're using MacPerl, simply select Run "hello" from the Script menu torun your first Perl program If you're not using MacPerl's built-in editor to writeyour program, use the Open command from the File menu to open your program
Trang 39When the Perl interpreter is all done reading your program from disk, it begins
to run the program and continues running that program until it's all done Whenit's finished with your program, the Perl interpreter exits and returns control toyour operating system
Now let's look at how the hello program is "run."
to the Perl interpreter If a Unix file begins with #! followed by the path of aninterpreter and is executable, Unix knows that this is a program (rather than ashell script) and how to interpret it See the "Q&A" section at the end of the hourfor an explanation of how to run programs
Some Web servers that can execute Perl programsApache, for examplealso payattention to the #! line and can call the programs without having to use an
explicit perl command
For now, just consider #! a comment line
The next line of the program is
Trang 40A whole lot is going on here This line constitutes a Perl statement; it marks offfor Perl one thing to do
First, this line contains a function called print The print function takeswhatever follows it and displays it to your screen by default What the print
function is supposed to print lasts all the way up to the semicolon (;)
The semicolon in Perl is a statement separator You should put a semicolon
between statements in your Perl program to show where one statement ends andthe next one begins
In this case, the print function displays the phrase Hello, World! The \n
at the end of the line tells Perl to insert a new blank line after it prints the phrase.The quotation marks around the phrase and the \n tell Perl that this is a literalstring, and not another function Strings are discussed at great length next hour
of a function name; pr int is not a valid function Nor can you insert them innumbers, as in 25 61 Also, whitespace inside literal strings like "Hello,World!" shows up as, well, whitespace Almost everywhere else it's valid Youcould write the sample Perl program like this: