Wrox Beginning Perl May 2000 ISBN 1861003145 pdf

Gratis

0
0
672
2 months ago
Preview
Full text

Simon Cozens

  His other Perl programs include a set of networking tools, aprogram to trap unsolicited email, and a series of varied Perl modules. He is currently working on a system to read English descriptions of markup languages and generate translators between them, andalso a Perl version of the TeX typesetting utility.

Peter Wainwright

  When he is not developing software or writing professionally, he spends much of his free time pursuing his interest in space tourism and maintaining the ever-growing Space Future website at www.spacefuture.com,which is based on a Linux server running Apache, naturally. Someday, he hopes he'll get the time to actually implement some of the stuff he writes about.

Summary of Contents

  6 How To Get Help 10 Perl Resources 13 Conventions 15 Downloading the Source Code 16 Exercises 16 Errata 17 Customer Support 17 Chapter 1: First Steps In Perl 19 Programming Languages 19 Interpreted vs. Compiled Source Code 20 Libraries, Modules and Packages 21 Why is Perl Such A Great Language?

Using References for Complex Data Structures 231

  Com 623 Index631 This work is licensed under the Creative Commons Attribution-NoDerivs-NonCommercial License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nd-nc/1.0 or send a letter to Creative Commons, 559 Nathan Abbott Way,Stanford, California 94305, USA.

A Potted History

  Larry is an Internet legend: Not only is he well-known for Perl, but as the author of the UNIX utilities rn, whichwas one of the original Usenet newsreaders, and patch, a tremendously useful utility that takes a list of differences between two files and allows you to turn one into the other. The syntax of the language is a lot more like a human language than the strict,rigid grammars and structures of other languages, so it doesn't impose a particular way of thinking upon you.

It's Free

  While Perl can be distributed under the terms of the GNU Public License (which you can find at http://www.gnu.org/ ), it can also be distributed under the Artistic License (found either with the perl sources or at http://www.opensource.org/licenses/), which purports to give more freedom to users andmore security to developers than the GPL. There's a question in the Perl FAQ (Frequently Asked Questions) about how to get a commercial version or support for Perl, and we'll see how you can find out the answer for yourselfpretty soon.

What Is Perl Used For?

  Perl is the powerbehind some of the most popular sites on the web: Slashdot (http://www.slashdot.org/), Amazon(http://www.amazon.com/), and Deja (http://www.deja.com/), and many others besides are almost entirely Perl-driven. Perl is becoming the de facto programming language of theInternet its networking capabilities have allowed it to be used to create clients, servers, and proxies for things such as IRC, WWW, FTP, and practically every other protocol you wish to think of.

Windows, UNIX, and Other Operating Systems

  If you need help with yourparticular platform, you will probably be able to find a README file for it in the Perl source distribution. You may also see the extension .pl in use for Perl programs (and, infact, I use it myself from time to time to remind me that a given program is in fact a Perl one), but to be really pedantic, that's more properly used for Perl 4 libraries.

The Prompt

What Do I Need To Use This Book?

  The 'shell prompt' (or just'prompt') refers specifically to the text that prompts you to enter a new program name, and more generally, to working with the shell instead of using a graphical interface. (Later in the introduction, we'll show how you can manually configure Windows to do this.) However, the window containing theoutput will disappear as soon as the program has finished (try it!), and you won't be able to see what's happened, so I encourage you to use the shell instead.

Installing on Linux/UNIX

  To do this, you need to type:> ln -sf /usr/local/bin/perl /usr/bin/perlIf you have obtained an RPM from your distributor, then you should be able to upgrade your existing perl installation using:> rpm -Uvh perl-5.6.0.613.rpm perl ####################### Building Perl from Source If none of these apply, you may have to build Perl from source. If you compile perl5 on a different machine or from a different object directory, copy the Policy.sh file from this object directory to thenew one before you run Configure -- this will help you with most of the policy defaults.

Installing on Windows

  Finally, close the Add New File Type dialog, and you should now be able to see the following window:Notice that your .plx file displays the pearl icon, which means that we are finished, and everything will work according to plan. Hit OK, and for confirmation, the extension, along with a pearl icon and the associated File Type, 'Perl File' should have appeared in the main list box.

How To Get Help

  UNIX people can get at the standard documentation as man pages (providing the MANPATHenvironment variable includes the correct location), and ActiveState users should be able to find the documentation under ActivePerl | Online Documentation on the Start menu. Here then is a list of those relevant to this book, in roughly the order we touch on the topics inthe book, plus one or two others that are handy and may satisfy your curiosity.

Websites

  This contains some good articles of interest to the Perl community and news fromPerl's major developers, as well as a wealth of links, tips, reviews, and documentation. It is also home to CPAN, the Comprehensive Perl Archive Network, a collection of ready-made programs, documents, notably the latest edition of the FAQ, some tutorials, and the Far More ThanEverything You Wanted To Know About (FMTEYWTKA) series of more technical notes.

Books

  If it's a block of code that you can type inas a program and run, then it's shown in a gray box like this: sub greeting {print "Hello, world!\n"; }Sometimes you'll see code in a mixture of styles, like this: sub greeting {print "Hello, world!\n"; }&greeting(); This is meant to draw your attention to code that's new or relevant to the surrounding discussion (in the gray box), while showing it in the context of the code you've seen before (on the white background). Whether you want to type the code in or not, we have made all the source code for this book available at our web site, at the following address:http://www.wrox.com If you're one of those readers who likes to type in the code, you can use our files to check the results you should be getting.

Exercises

  This book will give you the knowledge you need - but it is onlythrough practice that you will hone your skills and get a true feel for what Perl can help you achieve. You can find our suggested solutions to the exercises in Appendix H at the back of the book and also for download from http://www.wrox.com, but remember that there's more than one way to do it, sothey're not the only ways to solve the exercises.

Customer Support

  What does it mean to program?❑ What happens to the program that we write?❑ How do we structure programs and make them easy to understand?❑ How do computers see numbers and letters?❑ How do we find and eliminate errors in our programs? Usually, we'll specify the instructions in a file, which we edit with an ordinary text editor; sometimes, if we have a small program, we can get away with typing the wholething in at the command line.

Interpreted vs. Compiled Source Code

  The exact machine code produced depends on the processor of the computer and the operating system it runs, the translation would be very different for an x86 computer running WindowsNT compared to a Sun or Digital computer running Unix. ❑ Translate it to the native machine code of your computer, and run that instead.❑ Run it through a program that pretends to be the virtual machine and steps through the bytecode, and performs the appropriate actions.

Libraries, Modules, and Packages

  From now on, if we talk about a 'library', we'rereferring to the collection of files distributed with Perl, rather than Perl 4 library files; we won't be doing any work with library files (while library files have more or less been replaced by modules, they can stillbe useful) but will use the new-style modules instead. For a while, CGI was the standard way for a web server to communicate with other programs on the server, allowing the programs to do the hard work of generating content in a web page while the serverdedicated itself to pass that content onto browsers as fast as it could.

The Open Source Effort

  Anyone who can take the time to check the spelling or grammar of some of the coredocumentation can help, as can anyone who can think of a new way of explaining a concept, or anyone who can come up with a more helpful example for a function. The perlbug program, shipped with Perl, can be used to report problems to the list, but it's a good idea to check to makesure that it really is a problem and that it isn't fixed in a later or development release of Perl.

Developers Releases and Topaz

  To allow people to work on various areas of Perl at the same time and to avoid two people changing the same area in different ways, one person has to take responsibility for bits ofdevelopment, and all changes are to go through them. As well as bug fixes, the main thrust of development is to allow Perl to build more easily on a wider range of computers and to make better use of what the operating systemand the hardware provides for example support for 64-bit processors.

Keywords

  Instead of a full stop, a statement inPerl usually ends with a semicolon, as we saw above: print "Hello, world.\n";To print something again, we can add another statement: print "Hello, world.\n";print "Goodbye, world.\n"; There are times when you can get away without adding the semicolon, such as when it's absolutely clear to perl that the statement has finished. Surrounding the arguments with brackets clears things up a bit: print ("here ", "we ", "print ", "several ", "strings.\n"); We can also limit the amount of arguments we pass by moving the brackets: print ("here ", "we ", "print "), "several ", "strings.\n";We only pass three arguments, so they're the ones that get printed: here we printWhat happens to the others?

ASCII and Unicode

  As far as acomputer is concerned, everything is a number, and every character, albeit a letter or a symbol, is represented by a number in a sequence. Here arethe more common escape sequences: Escape Sequence Meaning \tTab \nStart a new line (Usually called 'newline') \bBack up one character ('backspace') \aAlarm (Rings the system bell) \x{1F18}Unicode character In the last example, 1F18 is a hexadecimal number (see 'Number Systems' just below) referring to a character in the Unicode character set, which runs from 0000-FFFF.

Number Systems If you thought the way computers see characters is complicated, we have a surprise for you

  The way most humans count is using the decimal system, or what we call base 10; we write 0, 1, 2, 3, 4,5, 6, 7, 8, 9, and then when we get to 10, we carry 1 in the 10s column and start from 0 again. Then when the 10s column gets to 9 and the 1s column gets to 9, we carry 1 in the 100s column and startagain.

The Perl Debugger

  While we will be showing you ways to avoid getting bugs in your program, Perl provides you with a tool to help find and trace the causes of bugs. Thankfully, Perl is a language that allows us a certain degree of freedom in our expression, and so long as we work within the bounds of the language, it won't enforce any particular method of expression onus.

Working with Simple Values

  The essence of programming is computation – we want the computer to do some work with the input(the data we give it). Finally in the chapter, we'll see one way of getting data from the user, and we'll use that to build our first 'useful' program.

Types of Data

  In the end, perl gave us a 'syntax error', which is the equivalent of it giving up in disgust saying, 'How do youexpect me to understand this?' Strings The other type of scalar available to us is the string, and we've already seen a few examples of them. The problem is that print is itself an operator as well, and the precedence of operators like print is highest of all.print as an operator takes a list of arguments and performs an operation (printing them to the screen).

Bitwise Operators

  First, let's have a look at the kind of numbers we're going to use in this section, just so we get used to them: 0 in binary is 0, but let's write it as 8 bits: 00000000 51 in binary is 0011001185 in binary is 01010101 170 in binary is 10101010204 in binary is 11001100 255 in binary is 11111111 Does it surprise you that 10101010 (170) is twice as much as 01010101 (85)? This compares pairs of bits as follows:1 and 1 gives 1 1 and 0 gives 00 and 1 gives 0 0 and 0 gives 0 For example, 51 & 85 looks like this: 51 0011001185 01010101 17 00010001Sure enough, if we ask Perl: #!/usr/bin/perl#bitop1.plx use warnings;print"51 ANDed with 85 gives us", 51 & 85, "\n"; The 'or' Operator As well as checking whether the first and the second bits are 1, we can check whether one or another is 1.

Truth and Falsehood

  "What is truth?" If we had asked that of a Perl programmer, we could be sure that he would have replied something like this: "Truth is anything that is not zero, an empty string, an undefined value, oran empty list."Later, we will want to perform actions based on whether something is true or false, for example if one number is bigger than another, or, unless a problem has occurred, or, while there is data left toexamine. So, we can write something like this: 4 >= 2 and print "Four is more than or equal to two\n";If the first test is true, perl has to check if the other side is true as well, and that means printing our message.

String Operators

  The precedence of the repetition operator is the same as the arithmetic operators, so if you're working outhow many times to repeat something, you're going to need brackets: #!/usr/bin/perl#string4.plx use warnings;print"Ba". When perl converts a string to a number, it takes any spaces, an optional minus sign, and then as many digits as it can from thebeginning of the string, and ignores everything else.

String Comparison

  In fact, it's more than alphabetical order: The computer is using either ASCII or Unicode internally to represent the string and has converted it to a series of numbers in the relevant sequence. The operator =>works like a comma with certain additional properties.❑ The =~ and !~ operators are used to 'apply' a regular expression to a string.❑ As well as providing an escape sequence and backwhacking special characters, \ is used to take a reference to a variable, to examine the variable itself rather than its contents.

Operator Precedence

  Here, finally, is a full table of precedence for all the operators we've seen so far, listed in descending order of precedence. Remember that if you need to get things done in a different order, you will need to use brackets.

Variables

  What we need to be able to do, and what variables allow us to do, is store a scalar away and refer to it again later. Now we can get at that data by simply using the variable's name: #!/usr/bin/perl#vars1.plx use warnings;$name = "fred"; print "My name is ", $name, "\n"; Lo and behold, our computer announces to us that:>perl vars1.plxMy name is fred>Now we're cut free at last from the problem of once-off data.

Multiple Assignments

  That is to say, it's trying to assign 1 to 4+$a, and you can only assign to a variable, not to an addition. The reason for this is that setting various different variables with different values in one go is complicated to read and just the sortof thing that gives Perl a bad name.

Scoping

  In this case, we have to change the last line to this:print "This is the ${times}th time.\n"; Now we get the right thing:>perl varint4.plx This is the 8th time.> Currency Converter Let's begin to wind up this chapter with a real example – a program to convert between currencies. So, in order to ask the user for a line of text, we say something like: print "Please enter something interesting\n";$comment = <STDIN>; This will read one line from the user and assign the string that was read to the variable $comment.

Lists and Hashes

  Just like the ingredients in a recipe or the pieces in a jigsaw, some things belong together ina natural sequence, for example, individual lines in a file, or the names of players in a squash ladder. They can be stored in another type of variable called an array, and we call each piece of data in the list an element.

Lists

  So, if you keep the maximum length of the lines in your source code to about 80columns (it's a good idea to keep your programs readable), one long string will wrap over, and you'll see this sort of thing:> perl mixedlist.plxHere is a list containing strings, (this one) numbers (3.6) and variables: 30>So if you're ever printing long strings, consider splitting it up into a list of smaller strings on separate lines as we've done above. So, since print needs to be passed a list, we make a list out of the element we want: print ( ('salt', 'vinegar', 'mustard', 'pepper')[2]); Try It Out – Months Of The Year We'll create a list of the months of the year, and then use a variable to access them.

Arrays

  If we force @array1 into scalar context, then the number of elements in the array is passed to print and not the contents of the array: Perl distinguishes between operations that want a list and operations that want a scalar. Since the pile of paper is a stack, the zeroth element (the letter), is at the bottom, and the notepad is at the top:my $hand; my @pileofpaper = ("letter", "newspaper", "gas bill", "notepad"); We use pop @array to remove the top element from the array and it returns that element, which we store in $hand.

Creating a Hash

  Investigate what happens when:There are more elements on the right than on the left.❑ ❑ There are more elements on the left than on the right.❑ There is a list on the left but a single scalar on the right.❑ There is a single scalar on the left but a list on the right. Assuming we have two numbers, stored in the variables $a and $b, here are the operators we can use for this:$a > $b $a is greater than $b$a < $b $a is less than $b$a == $b $a has the same numeric value as $b$a != $b $a does not have the same numeric value as $bDon't forget that the numeric comparison needs a doubled equals sign (==), so that Perl doesn't think you're trying to set $a to the value of $b:Also remember that Perl converts $a and $b to numbers in the usual way.

Logical Conjunctions

  Perl caters for both sets of thought patterns, and we could just as easily have written this:unless (exists $rates{$to}) { die "I don't know anything about {$to} as a currency\n";} The psychology is different, but the effect is the same: unless ($a) is effectively if (not ($a)). By using the fact that perl stops processing a logical conjunction when it knows the answer for definite, wecan create a sort of unless conditional: exists $rates{$to}or die "I don't know anything about {$to} as a currency\n"; How does this work?

Dokumen baru

Aktifitas terkini

Download (672 Halaman)
Gratis

Tags

Wrox Beginning Microsoft Visual Basic 2008 May 2008 Isbn 0470191341 Pdf Wrox Beginning Mysql Apr 2005 Isbn 0764579509 Pdf Wrox Beginning Unix Apr 2005 Isbn 0764579940 Pdf Wrox Professional Perl Programming Feb 2001 Isbn 1861004494 Pdf Wrox Beginning Regular Expressions Feb 2005 Isbn 0764574892 Pdf Wrox Beginning Database Design Dec 2005 Isbn 0764574906 Pdf Wrox Professional Xml Databases Jan 2000 Isbn 1861003587 Pdf Wrox Beginning Xml 2Nd Edition Dec 2001 Isbn 0764543946 Pdf Wrox Professional Xml 2Nd Edition May 2001 Isbn 1861005059 Pdf Wrox Professional Apache Tomcat 5 May 2004 Isbn 0764559028 Pdf
Show more