Sams Teach Yourself Laura Lemay's Teach Yourself PERL in 21 Days

Overview

In just 21 days, you'll learn all the skills you need to easily write, debug, and run your own Perl scripts. Each day's lesson covers a different aspect of Perl in an easy to understand, step-by-step manner, reinforcing the discussion of techniques and concepts with practical working examples.
Read More Show Less
... See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (24) from $1.99   
  • New (2) from $50.00   
  • Used (22) from $1.99   
Close
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
$50.00
Seller since 2014

Feedback rating:

(149)

Condition:

New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
$50.00
Seller since 2014

Feedback rating:

(149)

Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Close
Sort by
Sending request ...

Overview

In just 21 days, you'll learn all the skills you need to easily write, debug, and run your own Perl scripts. Each day's lesson covers a different aspect of Perl in an easy to understand, step-by-step manner, reinforcing the discussion of techniques and concepts with practical working examples.
Read More Show Less

Product Details

  • ISBN-13: 9780672313059
  • Publisher: Sams
  • Publication date: 3/23/1999
  • Series: Sams Teach Yourself Series
  • Edition description: Older Edition
  • Edition number: 1
  • Pages: 680
  • Product dimensions: 7.39 (w) x 9.12 (h) x 1.66 (d)

Meet the Author


Laura Lemay is one of the world's most popular authors on Web development topics. She is the author of the best-selling Sams Teach Yourself Java in 21 Days and Sams Teach Yourself Web Publishing with HTML in a Week. She is known for her ability to clearly explain even the most difficult technical topics, while complementing her discussions with interesting yet practical examples.
Read More Show Less

Read an Excerpt


Day 1: An Introduction to Perl

Greetings and welcome to Sams Teach Yourself Perl in 21 Days! Today, and for the next 20 days, I'll be your guide to all things Perlish. By the time you finish this book-or at least by the time you put it down-you should know enough Pert to accomplish just about anything you'd like to do and to converse intelligently with other Pert programmers.

Today we're going to start with some basic information to ease you into working with Pert. Today's lesson is kind of short, just enough to give you a little background and to get you started using Pert with some simple scripts. In particular, you'll learn

  • Some background on Pert: what it is, who created it, who's working on it now.
  • Why you should learn Pert (reasons besides "my boss told me to").
  • Some actual Pert code, so you can get an idea for how Pert is written and run (and be prepared for the rest of this week's lessons).

And so, without further ado, let's get started. Week one, chapter one, section one-Onward!

What Is Perl and Where Did It Come From?

Perl is not a typo for pearl. Perl is actually an acronym. It stands for Practical Extraction and Report Language, which is a pretty good description of what Perl does particularly well: Extraction for looking at files and pulling out the important parts (for example, the actual data from an HTML file, or the user or host names from a networking log file); and report for generating output and, well, reports, based on the information that was found. It's a practical language because it's much easier to write these sorts of programs in Perl than it would be in a language such as C. But no one really gets hung up on the acronym any more; Perl is just Perl.

Perl was created in 1987 by Larry Wall, who at the time was already well known in the UNIX software world for having written the freely available patch program as well as the Usenet newsreader rn. The story goes that Larry was working on a task for which the UNIX program awk (the popular extraction and report language of the time) wasn't powerful enough, but he realized the task would take a whole lot of work to accomplish in a language such as C. So Perl was created as a scripting language that borrows bits from various other UNIX tools and languages, such as sed, grep, awk, shell scripting and, yes, C. Also, as with patch and rn, Perl was released for free to the UNIX community. And the UNIX community said it was good.

For many years, Perl was the language of choice for UNIX system administrators and other UNIX programmers who needed a flexible, quick-to-prograrn language to accomplish tasks for which a language such as C would be overkill (or take too much work), or for tasks that were too complex for shell scripting. It was because of its existing popularity as a UNIX language that Perl became popular as a Web language for creating CGI scripts-most early Web servers ran on UNIX systems. CGI (Common Gateway Interface) allowed programs and scripts to be run on the Web server in response to forms or other input from Web pages. Perl fit neatly into that niche, and in the last couple of years as the Web and CGI have become more and more popular, the interest in the Perl language has also grown dramatically. Even as Web servers have ended up being run on systems other than UNIX, Perl moved with them and continued to be popular in this realm.

Larry Wall originally "owned" Perl and was responsible with keeping it updated and incorporating new changes. With Perl's recent surge in popularity, however, the task of maintaining Perl now falls to a close-knit group of volunteer programmers. These programmers, including Larry Wall, maintain the core Perl source, port the source to platforms other than UNIX, coordinate bug fixes, and establish the "standard" Perl release (the Changes file in the standard Perl distribution lists the primary dramatis personae of Perl). No single organization owns Perl; like the GNU tools (GNU emacs, GCC, GDB, and so on) and the Linux operating system, Perl is defined and managed on a volunteer, goodwill basis. It's also available free of charge; all you have to do is download and install it.

The current major version of Perl is Perl 5, and it is the version this book covers. All Perl releases also have minor versions with various numbers and letters, which most commonly fix bugs that were found in the original release (although some new features do creep into the minor version releases). The current UNIX and Windows version of Perl as I write this book is 5.005, with the Macintosh version at 5.004. These minor numbers may have changed by the time you read this, as work is ongoing on all the Perl ports (and at any time, there may be separate releases for less stable beta versions as well as the current "official" version). For the most part, however, the minor version is less important than making sure you have some version of Perl 5 installed.

Note: As of Perl 5.005, support for Windows was folded into the core source code Note: The examples in this book were written on the UNIX version of Perl, version

Why Learn Perl?

There are an enormous number of programming languages available on the market today, all of which seem to claim to be able to solve all your problems in half the time, at a quarter of the cost, and then bring about world peace, too. So why learn Perl over another one of those vaunted languages?

The best reason is that different tools are best for different tasks, and Perl is particularly good at a number of common tasks. But there are a number of other good reasons to learn and use Perl.

Perl Is Useful

How's that for a good reason? Perl is probably the language for you if any of the follow- ing profiles describes you.

  • You're a system administrator looking for a general-purpose scripting language.
  • You're a Web administrator with a dozen CGI programs that your Web designers want you to write.
  • You're a fairly well-versed UNIX user looking to expand your knowledge.
  • You're a programmer looking to quickly prototype a more complicated program.
  • You just want a language that will let you hack around with stuff. You can do real work in Perl, and you can get it done right away.

Perl Doesn't Need Any Fancy Software

To use Perl, you do not need to buy a nifty shrink-wrapped Perl program. You don't need a Perl compiler or an integrated Perl development environment. You don't need a browser that supports Perl or a computer that says "Perl Inside." All you need is one thing: the standard Perl interpreter. You can get that for free, simply by downloading it. If you've got a UNIX shell account with an ISP, you've probably already got it.

OK, there is one other thing you need: You must have a text editor in which to write your Perl scripts. One of these comes with just about every system you can run Perl on, so you're still safe.

You Can Program Perl Quickly

Perl is a scripting language, which means that your Perl scripts are just text files, and they're executed on the fly when Perl runs them. You don't have to use a compiler to convert your code to some other format like an executable or a bytecode file, as you would for a language such as C or Java. This makes Perl quicker to get running for inital programs, makes the debugging process faster, and also allows you to modify your Carl scripts quicker and easier than in C.

Note: Scripting languages are often called interpreted languages in Computer scripts right away as you can with an interpreted language, it also gives you some measure of control over the compilation process. Perl also runs faster than a pure interpreted language does (although not as fast as a compiled language).

Perl Is Portable

Because Perl is a scripting language, a Perl script is a Perl script is a Perl script regardless of which platform you run it on. Although there are differences in Perl on different platforms and features that work only on some platforms (I'll point those out as we run across them), in many cases moving a script from one platform to another can be done without modifying the script in any way whatsoever-without having to laboriously port to a new operating system, without even having to recompile your source code.

Perl Is Powerful

Perl was designed to be a superset of many fairly complex UNIX tools. It's also got all the features you'd expect in a high-level language (and many you wouldn't). Most everything you can do in a sophisticated language such as C, you can do in Perl, although there are, of course, tasks for which C would be better than Perl, and vice versa. You can do simple top-to-bottom scripts in Perl. You can do structured programming in Perl. You can do advanced data structures in Perl. You can do object-oriented programming in Perl. It's all there.

If Perl alone isn't good enough for you, there are also extensive archives of various tools and libraries (called modules) to do various common tasks in Perl. Modules to do database interaction, networking, encryption, ties to other languages-just about everything you can think of-are available in these archives. In many cases, if you think, "I need to do X in Perl"' someone has already done X and put their code in the archives for you to use. Perl's cooperative nature means that there is an enormous amount of resources for you to take advantage of.

Perl Is Flexible

One of the mottoes of Perl is: "There's more than one way to do it." (This is commonly referred to by Perl folk as the acronym TMTOWTDI). Remember this phrase, because IT be coming back to it throughout the book. The Perl language was designed around the idea that different programmers have different ways of approaching and solving problems. So instead of you having to learn how to adapt your thinking to a small set of commands and syntactical constructs (as in C or Java), the Perl language has an enormous number of constructs and shortcuts and side effects-many of which accomplish the same thing other constructs do, but in slightly different ways.

This does make Perl a very large, complex, complicated language (when I first encountered Perl as a young and idealistic programmer, my first reaction was "It's so UGLY!"). But Perl's size and depth of features also make Perl extremely flexible and fun to use. You can write a very straightforward, C-like Perl script-one that uses some of Perl's various shortcuts, while still being entire readable-or one that relies so heavily on Perl side effects and hidden features that you can make other programmers' heads explode just trying to read it (sometimes that can be a fun way to spend a quiet afternoon). It's your choice how you want to use Perl-you don't have to modify your thinking to fit the language. (These days, I still occasionally think Perl is ugly-but I also think it's really cool and fun to work in. I can't say that about C, which is a more consistent and elegant language, but seems to involve a lot more drudgery)....

Read More Show Less

Table of Contents

Introduction 1
Week 1 Getting Started 5
1 An Introduction to Perl 7
2 Working with Strings and Numbers 29
3 More Scalar Data and Operators 51
4 Working with Lists and Arrays 71
5 Working with Hashes 97
6 Conditionals and Loops 117
7 Exploring a Few Longer Examples 147
Week 2 Doing More 163
8 Manipulating Lists and Strings 165
9 Pattern Matching with Regular Expressions 191
10 Doing More with Regular Expressions 221
11 Creating and Using Subroutines 247
12 Debugging Perl 279
13 Scope, Modules, and Importing Code 297
14 Exploring a Few Longer Examples 329
Week 3 Advanced Perl 357
15 Working with Files and I/O 359
16 Using Perl for CGI Scripting 387
17 Managing Files and Directories 417
18 Perl and the Operating System 435
19 Working with References 467
20 Odds and Ends 505
21 Exploring a Few Longer Examples 539
App. A Perl Functions 567
App. B A Survey of Perl Modules 605
App. C Installing Perl on a UNIX System 625
App. D Installing Perl for Windows 635
App. E Installing Perl for the Macintosh 641
Index 647
Read More Show Less

First Chapter

[Figures are not included in this sample chapter]

Sams Teach Yourself Perl in 21 Days
- 3 -
More Scalar Data and Operators

Scalar data, as you learned yesterday, involves individual items such as numbersand strings. Yesterday, you learned several things you could do with scalar data;today, we'll finish up the discussion, show you more operators you can play with,and finish up with some related topics. The things you can expect to learn todayare

  • Various assignment operators
  • String concatenation and repetition
  • Operator precedence
  • A short overview of input and output

Assignment Operators

Yesterday, we discussed the basic assignment operator, =, which assigns a valueto a variable. One common use of assignment is an operation to change the value ofa variable based on the current value of that variable, such as:

$inc = $inc + 100;

This does exactly what you'd expect; it gets the value of $inc, adds 100 to it,and then stores the result back into $inc. This sort of operation is so common thatthere is a shorthand assignment operator to do just that. The variable referencegoes on the left side, and the amount to change it on the right, like this:

$inc += 100;

Perl supports shorth and assignments for each of the arithmetic operators, forstring operators I haven't described yet, and even for && and ||. Table 3.1shows a few of the shorthand assignment operators. Basically, just about any operatorthat has two operands has a shorthand assignment version, where the general ruleis that


variable 
operator= 
expression

is equivalent to


variable = 
variable 
operator 
expression

There's only one difference between the two: in the longhand version, the variablereference is evaluated twice, whereas in the shorthand it's only evaluated once.Most of the time, this won't affect the outcome of the expression, just keep it inmind if you start getting results you don't expect.

TABLE 3.1  SOME COMMON ASSIGNMENT OPERATORS

Operator Example Longhand Equivalent
+=
$x += 10
$x = $x + 10
-=
$x -= 10
$x = $x - 1 0
*=
$x *= 10
$x = $x * 10
/=
$x /= 10
$x = $x / 10
%=
$x %= 10
$x = $x % 10
**=
$x **= 10
$x = $x**10

Increment and Decrement Operators

As in C, the ++ and -- operators are used with a variable to increment or decrementthat variable by 1 (that is, to add or subtract 1). And as with C, both operatorscan be used either in prefix fashion (before the variable, ++$x) or in postfix (afterthe variable, $x++). Depending on the usage, the variable will be incremented ordecremented before or after it 's used.

If your reaction to that above paragraph is "Huh?", here's a wordierexplanation. The ++ and -- operators are used with scalar variables to incrementor decrement the value of that variable by 1, sort of an even shorter shorthand tothe += or -= operators. In addition, both operators can be used before the variablereference--called prefix notation, like this:

++$x;

Or in postfix notation (after the variable), like this:

$x++;

The difference is subtle, and determines when in the process of Perl's evaluationof an expression that the variable actually gets incremented. If you used these operatorsas I did in those previous two examples--alone, by themselves--then there is no difference.The variable gets incremented and Perl moves on. But, if you use these operatorson the right side of another variable assignment, then whether you use prefix orpostfix notation can be significant. For example, let's look at this snippet of Perlcode:

$a = 1;$b = 1;$a = ++$b;

At the end of these statements, both $a and $b will be 2. Why? The prefix notationmeans that $b will be incremented before its value is assigned to $a. So the orderof evaluation in this expression is that $b is incremented to 2 first, and then thatvalue is assigned to $a.

Now let's look at postfix:

$a = 1;$b = 1;
$a = $b++;

In this case, $b still ends up getting incremented; its value is 2. But $a's valuestays at 1. In postfix notation, the value of $b is used before it's incremented.$b evaluates to 1, that value is assigned to $a, and then $b is incremented to 2.


NOTE: To be totally, rigorously correct, my ordering of ho w things happen here is off. For a variable assignment, everything on the right side of the = always has to be evaluated before the assignment occurs, so in reality, $a doesn't get changed until the very last step. What actually happens is that the original value of $b is remembered by Perl, so that when Perl gets around to assigning a value to $a, it can use that actual value. But unless you're working with really complex expressions, you might as well think of it as happening before the increment.

String Concatenation and Repetition

String and text management is one of Perl's biggest strengths, and quite a lotof the examples throughout this book are going to involve working with strings--findingthings in them, changing things in them, getting them from files and from the keyboard,and sending them to the screen, to files, or over a network to a Web browser. Today,we started by talking about strings in general terms.

There are just a couple more things I want to mention about strings here, however,because they fit in with today's "All Operators, All the Time" theme. Perlhas two operators for using strings: . (dot) for string concatenation, and x forstring repetition.

Unlike Java, which uses the + operator for both addition and for string concatenation,Perl reserves + for use with numbers; to add together two strings you use the . operator,like this:

`four score' . ` and twenty years ago';

This expression results in a third string containing `four score and seven yearsago.' It does not modify either of the original strings.

You can string together multiple concatenations, and they'll result in one s inglelong string:

`this, ` . `that, ` . `and the ` . `other thing.'

The other string-related operator is the x operator (not the X operator; it mustbe a lowercase x). The x operator takes a string on one side and a numberon the other (but will convert them as needed), and then creates a new string withthe old string repeated the number of times given on the right. Some examples:

`blah' x 4;  # `blahblahblahblah'`*' x 3;   # `***'10 x 5;   # `1010101010'

In that last example, the number 10 is converted to the string `10' and then repeatedfive times.

Why is this useful? Consider having to pad a screen layout to include a certainnumber of spaces or filler characters, where the width of that layout can vary. Orconsider, perhaps, doing some kind of ASCII art where the repetition of characterscan produce specific patterns (hey, this is Perl, you're allowed--no, encouraged--todo weird stuff like that). At any rate, should you ever need to repeat a string,the x operator can do it for you.

Operator Precedence and Associativity

Operator precedence determines which operators in a complex expressionare evaluated first. Associativity determines how operators that have thesame precedence are evaluated (where your choices are left-to-right, right-to-left,or nonassociative for those operators where order of evaluation is either not important,not guaranteed, or not even possible). Table 3.2 shows the precedence and associativityof the various operators available in Perl that you've learned about yesterday andtoday, with operators of a higher precedence (evaluated first) higher up in the tablethan those of a lower precedence (evaluated later). You'll want to fold down thecorner of this page or mark it with a sticky note; this is one of those tables you'llprobably refer to over and over again as you work with Perl.

You can always change the evaluation of an expression (or just make it easierto read) by enclosing it with parentheses. Expressions inside parentheses are evaluatedbefore those outside parentheses.

Note that there are a number of operators in this table you haven't learned aboutyet (and some I won't cover in this book at all). I've included lesson referencesfor those operators I do explain later on in this book.

TABLE 3.2  OPERATOR PRECEDENCE AND ASSOCIATIVITY

Operator Associativity What It Means
->
left Dereference operator (Day 19, "Working with References")
++ --
non Increment and decrement
**
right Exponent
! ~ \ + -
right Logical not, bitwise not, reference (Day 19), unary +, unary -
=~ !~
left Pattern matching (Day 9, "Pattern Matching with Regular Expressions")
* / % x
left Multiplication, division, modulus, string repeat
+ - .
left Add, subtract, string concatenate
<< >>
left Bitwise left shift and right shift
unary operators
non Function-like operators
< > <= >= lt gt lt le
non Tests
== != <=> eq ne cmp
non More tests (<=> and cmp, Day 8, "Manipulating Lists and Strings")
&
left Bitwise AND
| ^
left Bitwise OR, bitwise XOR
&&
left C-style logical AND
||
left C-style logical OR
..
non Range operator (Day 4, "Working with Lists and Arrays")
?:
right Conditional operator (Day 6, "Conditionals and Loops")
= += -= *= /=, etc.
right Assignment operators
, =>
left Comma operators (Day 4)
list operators
non list operators in list context (Day 4)
not
right Perl logical NOT
and
left Perl logical AND
or xor
left Perl logical OR and XOR

An Example: Simple Statistics

Here's an example called stats.pl, which prompts you for numbers, one at a time.Once you're done entering numbers, it gives you a count of the numbers, the sum andthe average. It's a rather silly kind of statistics script, but it'll demonstratetests and variable assignment (and we'll be building on this script later on). Here'san example of what it looks like when run:

% 
stats.plEnter a number: 
3Enter a number: 
9Enter a number: 
3Enter a number: 
7Enter a number: 
4Enter a number: 
7Enter a number: 3Enter a number:Total count of numbers: 7Total sum of numbers: 36Average: 5.14%

NOTE: As with the temperature conversion example we did yesterday, I'm making the rather large assumption here that all the input you get will actually be numbers. An accidental (or intentional) string as part of the input will result in Perl warnings and potential errors. Later on in this week, you'll learn more about input validation; for the time being, let's assume we have nothing but good data to work with.

Listing 3.1 shows the code behind the statistics script.

LISTING 3.1  THE stats.pl SCRIPT

1: #!/usr/bin/perl -w2:3: $input = `'; # temporary input4: $count = 0; # count of numbers5: $sum = 0;  # sum of numbers6: $avg = 0;  # average7:8: while () {9:  print `Enter a number: `;10:  chomp ($input = <STDIN>);11:  if ($input ne `') {12:   $count++;13:   $sum += $input;14:   }15:  else { last; }16: }17:18: $avg = $sum / $count;19:20: print "\nTotal count of numbers: $count\n";21: print "Total sum of numbers: $sum\n";22: printf("Average (mean): %.2f\n", $avg);

This script has three main sections: an initialization section, a section forgetting and storing the input, and a section for computing the average and printingout the results.

Here's the initialization section (with line numbers in place):

3: $input = `'; # temporary input4: $count = 0; # count of numbers5: $sum = 0;  # sum of numbers6: $avg = 0;  # average

We're using four scalar variables here, one to store the input as it comes in,one to ke ep track of the count of numbers, one to hold the sum and one to hold theaverage.

The next section is where you prompt for the data:

8: while () {9:  print `Enter a number: `;10:  chomp ($input = <STDIN>);11:  if ($input ne `') {12:   $count++;13:    $sum += $input;14:   }15:  else { last; }16: }

This second part of the script uses a while loop and an if conditional to readthe input repeatedly until we get a blank line. I still haven't discussed how theseare defined in Perl (and we won't get around to it until Day 6) but if you've seenwhiles and ifs before this shouldn't give you too much pause. The while loop hasno ending test (the parentheses in line 8 are empty), which makes it an infiniteloop.

Inside the body of the while, we use line 10 to grab the actual input (and I knowyou're still waiting to learn what chomp and <STDIN> do; it's coming up soon).Lines 11 through 15 test to make sure that the input actually contains something.Note the test in line 11, which is a string test (ne), not a number test.

If there is input to be handled, we increment the $count variable, and modifythe $sum variable to add the new value that was input. With these two lines (12 and13) we can keep a running total of the count and the sum as each new bit of inputcomes along, but we'll wait until the end of the loop to calculate the average.

Line 15 has the else clause of the conditional--if there was no input in the line,then we'll break out of the infinite while loop with the last keyword (you'll learnmore about last when you learn about loops in Day 6).

And, finally, we finish up by calculating the average and printing the results:

18: $avg = $sum / $co unt;19:20: print "\nTotal count of numbers: $count\n";21: print "Total sum of numbers: $sum\n";22: printf("Average (mean): %.2f\n", $avg);

Line 18 is a straightforward calculation, and lines 20 through 22 print the count,the sum, and the average. Note the \n at the beginning of the first print statement;this will print an extra blank line before the summary. Remember that \n can appearanywhere in a string, not just at the end.

In the third summary line, you'll note we're using printf again to format thenumber output. This time, we used a printf format for a floating-point number thatprints 2 decimal places of that value (%.2f). You get more information about printfin the next section.

Input and Output

We'll finish up today with two topics that initially might not seem to fit witheverything else we've talked about concerning scalar data: handling simple inputand output. I've included them here essentially for one reason: so you know what'sbeen going on in the scripts you've been writing that read input from the keyboardand print output from the screen.

In this section we'll talk about simple input and output, and as the book progressesyou'll learn more about input and output to disk files, culminating on Day 15, "Workingwith Files and I/O."

File Handles and Standard Input and Output

First, some terminology. In the scripts you've been looking at today and yesterday,you've used Perl code to read input from the keyboard and to write output to thescreen. In reality, the keyboard and the screen aren't the best termsto use because, actually, you're reading from a source called standard inpu t,and writing to a destination called standard output. Both of these conceptsare borrowed from UNIX systems, where using pipes and filters and redirection arecommon, but if you're used to Windows or the Mac, the idea of a standard input oroutput may not make much sense.

In all cases, when you're reading data from a source, or writing data to a destination,you'll be working with what are called file handles. Most often, file handlesrefer to actual files on the disk, but there are instances where data may becoming from or going to an unnamed source, for example, from or to another programsuch as a Web server. To generalize data sources and destinations that are not actualfiles, Perl gives you built-in file handles for standard input and standard outputcalled STDIN and STDOUT (there's also STDERR, for standard error, but we'll leavethat for later). These two file handles happen to include (and, in fact, are mostcommonly used for) input from the keyboard and output from the screen.

Reading a Line from Standard Input with <STDIN>

In the scripts we've seen so far in this book, there's usually been a line forreading input from the keyboard that looks something like this:

chomp($inputline = <STDIN>);

You'll see that line a lot in Perl code, although often it occurs on multiplelines, something like this (the two forms are equivalent):

$inputline = <STDIN>;chomp($inputline);

You know now that $inputline is a scalar variable, and that you're assigning somethingto it. But what?

The STDIN part of this line is the special built-in file handle for standard input.You don't have to do anything to open or man age this special file handle; it's therefor you to use. In case you're wondering why it's in all caps, that's a Perl conventionto keep from confusing file handles from other things in Perl (such as actual keywordsin the language).

The angle brackets around <STDIN> are used to actually read input from afile handle. The <> characters, in fact, are often called the input operator.<STDIN>, therefore, means read input from the STDIN file handle. Inthis particular case, where you're assigning the <STDIN> expression to a scalarvariable, Perl will read a line from standard input and stop when it gets to a newlinecharacter (or a carriage return on the Macintosh). Unlike in C, you don't have toloop through the output and watch every character to make sure it's a newline; Perlwill keep track of that for you. All you need is <STDIN> and a scalar variableto store the input line in.


NOTE: The definition of what a line is, <STDIN> is actually determined by Perl's input record separator, which is a newline character by default. On Day 9 you'll learn how to change the input record separator. For now, just assume that the end of line character is indeed the end of a line and you'll be fine.

All this talk about input and outut brings us to the somewhat amusingly-namedchomp function. When you read a line of input using <STDIN> and store it ina variable, you get all the input that was typed, and the newline character at theend as well. Usually, you don't want that newline character there, unless you'reprinting the input right back out again and it's useful for formatting. The built-inPerl chomp fun ction, then, takes a string as input, and if the last character isa newline, it removes that newline. Note that chomp modifies the original stringin place (unlike string concatenation and other string-related functions, which createentire new strings and leave the old strings alone). That's why you can call chompby itself on its own line without reassigning the variable that holds that string.


NOTE: Previous versions of Perl used a similar function for the same purpose called chop. If you read older Perl code, you'll see chop used a lot. The difference between chomp and chop is that chop indiscriminately removes the last character in the string, whether it's a newline or not, whereas chomp is safer and doesn't remove anything unless there's a newline there. Most of the time, you'll want to use chomp to remove a newline from input, rather than chop.

Writing to Standard Output with print

Once you get input into your Perl script with <STDIN>, or from a file orfrom wherever, you can use Perl statements to do just about anything you like withthat input. The time comes, then, when you'll want to output some kind of data aswell. You've already seen the two most common ways to do that: print and printf.

Let's start with print. The print function can take any number of arguments andprints them to the standard output (usually the screen). Up to this point we've onlyused one argument, but you can also give it multiple arguments, separated by commas.Multiple arguments to print, by default, will get concatenated together before theyget printed:

print `take THAT!';print 1, 2, 3;    # prints `123'$a = 4;p rint 1, ` `, $a;  # prints "1 4"print 1, " $a";    # same thing

NOTE: I say by default because multiple arguments to print actually form a list, and there is a way to get Perl to print characters in between list elements. You'll learn more about this tomorrow on Day 4.

I mentioned the STDOUT file handle earlier, as the way to access the standardoutput. You may have noticed, however, that we've been printing data to the screenall along with print, and we've never had to refer to STDOUT. That's because Perl,to save you time and keystrokes, assumes that if you use print without an explicitfile handle, you want to use standard output. In reality, the following Perl statementsdo exactly the same thing:

print "Hello World!\n" ;
print STDOUT "Hello World!\n";

More about the longer version of print when you learn more about file handlesthat are attached to actual files, on Day 15.

printf and sprintf

In addition to the plain old workhorse print, Perl also provides the printf andsprintf functions, which are most useful in Perl for formatting and printing numbersin specific ways. They work almost identically to those same functions in C, butbeware: printf is much less efficient than print, so don't just assume you can useprintf everywhere because you're used to it. Only use printf when you have a specificreason to do so.

As you learned yesterday, you use the printf function to print formatted numbersand strings to an output stream, such as standard output. sprintf formats a stringand then just returns that new string, so it's more u seful for nesting inside otherexpressions (in fact, printf calls sprintf to do the actual formatting).

Both printf and sprintf take two or more arguments: the first, a string containingformatting codes, and then one or more values to plug into those codes. For example,we've seen examples of printf that rounded off a floating-point integer to two decimalplaces, like this:

printf("Average (mean): %.2f", $avg);

We've seen one that rounded it to the nearest integer, like this:

printf("%d degrees Celsius\n", $cel);
Yesterday, you also saw how to use sprintf to round a floating-point number to two digits of precision:
$value = sprintf("%.2f", $value);

The format codes follow the same rules as the C versions (although the * lengthspecifier isn't supported) and can get quite complex. A simple formatting code thatyou might use in Perl looks like this:

%l.px

The x part is a code referring to the type of value; in Perl you'll be most interestedin the d formatting code for printing integers, and the f formatting code for printingfloating-point numbers. The l and the p in the formatting code are both optional.l refers to the number of characters the value should take up in the final string(padded by spaces if the value as printed is less than l), and p is the number ofdigit precision of a floating-point number. All numbers are rounded to the appropriateprecision.

Here are some typical examples of how either sprintf or printf might be used:

$val = 5.4349434;printf("->%5d\n", $val);  # ->   5printf("->%11.5f\n", $val); # ->  5.43494printf("%d\n", $val);   # 5printf("%.3f\n", $val);  # 5.435printf("%.1f\n", $val);  # 5.4

Multiple formatting codes are interpolated left to right in the string, each formattingcode replaced by an argument (there should be an equal number of formatting codesand extra arguments):

printf("Start value : %.2f End Value: %.2f\n", $start, $end);

In this example, if $start is 1.343 and $end is 5.33333, the statement will printthis:

Start value : 1.34 End Value: 5.33

If you're unfamiliar with C's printf formatting codes, you might want to referto the perlfunc man page (or the printf man page) for more details.

A Note About Using Functions

Now that you've learned about the print and chomp functions, as well as had aglimpse of other functions such as oct and int and sprintf, this is a good time togo over how function calls work. If you've been paying careful attention, you mayhave noticed that I've been calling the print function like this:

print "Hello, World!\n";

I've also been calling chomp and printf like this:

chomp($input = <STDIN>);printf("Average (mean): %.2f", $avg);

One form has parentheses around the arguments to the function, the other formdoesn't. Which is correct? The answer is both. Parentheses around the argumentsto a function are optional; as long as Perl can figure out what your arguments are,either form works just fine.

In this book, I've used a smattering of both. My general rule is that if a functiontakes one argument--int or oct being good examples--I'll leave off the parentheses.If it takes multiple arguments or if its argument is an expression ( printf, or chomp),then I use parentheses. The print function can go either way depending on the situation.

Depending on what you're familiar with--and what looks right to you--feel freeto pick your own rule for parenthesizing functions in your own scripts. I shouldmention, however, that the rule of parentheses being optional "as long as Perlcan figure out what your arguments are," can occasionally be tricky to figureout, particularly with multiple arguments and particularly when some of them areparenthesized expressions or lists. To make it even more complex, some of Perl'sbuilt-in functions are actually operators, and have a different precedence from actualfunction calls (see the next section, "Going Deeper," for more information).There are rules of precedence to determine exactly how complex function calls areto be evaluated, but the safest solution, if Perl appears to be ignoring your argumentsor producing weird results, is to include parentheses around all the arguments. Turningon Perl warnings will also help catch some of these problems.

Going Deeper

Had enough of strings and numbers yet? Want to learn more? No problem. This sectionhas a number of other features to look at concerning scalar data before we forgeon ahead to lists.

Operators are all discussed in the perlop man page; functions in the perlfuncman page. As I mentioned before, you can get to all these pages through the use ofthe perldoc command or on the Web at http://www.perl.com/CPAN-local/doc/manual/html/pod/.

Useful Number and String Functions

Perl includes quite a few built-in functions for a variety of purposes. AppendixA, "Perl Functions," contains a summary of those functions, and the perlfuncman page also describes them in further detail. In particular, Perl includes a numberof useful functions for numbers and strings, including those summarized in Table3.3. We'll explore some of these in more detail in forthcoming chapters; others you'llhave to explore on your own.

TABLE 3.3  NUMBER AND STRING FUNCTIONS

Function What It Does
abs
Absolute value
atan2
Arctangent
chr
The character represented by a number in the ASCII character set
cos
Cosine
exp
e to the power of (use ** for exponentiation)
int
Truncate decimal part of a float
index
Returns the position of the first occurrence of the substring in string
lc
Lowercase a string
lcfirst
Lowercase the first character in a string
length
Length (number of bytes)
log
Logarithm
ord
The number of a character in the ASCII character set
rand
Random number
reverse
Reverse a scalar
rindex
Reverse index (starts from end of string)
sin
Sine
sqrt
Square root
substr
Returns a substring starting at an offset of some length
uc
Uppercase a string
ucfirst
Uppercase the first letter in a string

Bitwise Operators

Perl provides the usual set of C-like operators for twiddling bits in integers:~, <<, >>, &, |, and ^, as well as assignment shortcuts for thoseoperators. See the perlop man page for specifics.

The cmp and <=> Operators

In addition to the relational operators I described in the section on comparisons,Perl also has the <=> and cmp operators. The former is for numbers, and thelatter for strings. Both return -1, 0, or 1 depending if the left operator is greaterthan the right, the operators are equal, or if the right operator is greater thanthe left, respectively. These operators are most commonly used for creating sortroutines, which you'll learn more about on Day 8.

Functions and Function-Like Operators

Perl's built-in functions actually fall into two groups: functions that are functions,and operators that take one argument and masquerade as functions. The function-likeoperators fall in the middle of the precedence hierarchy and behave like operatorsin this respect (whereas function calls with parentheses always have the highestprecedence). See the perlop man page under "Named Unary Operators" fora list of these functions.

Summary

Today was Part 2 of everything you ever wanted to know, and probably a whole lotyou didn't, about scalar data. Today you got to look at more tables of operators,in particular operators for assigning things to variables, or changing the valuesof variables, and for concatenating and repeating strings. You also learned aboutoperator precedence, which determines which operators get to go first when you havean expression with lots of them in it.

We finished up today's lesson talking about input and output, and in particularusing <STDIN> to get data into a Perl script and the various print functionsto print it out again. You also learned a bit about calling functions with and withoutparentheses around their arguments.

The built-in functions you learned about today include (see the perlfunc man pageor Appendix A for more details about these functions).

  • print takes a list of comma-seperated values and strings to print and outputs those values to the standard output (STDOUT).
  • printf takes a formatting string and any number of values, and prints those values according to the codes i n the formatting string.
  • sprintf does the same thing as printf, except it returns the formatted string without printing anything.
  • chomp with a string argument removes any trailing newlines from that string and returns the number of characters it deleted.
  • chop is the older version of chomp; it removes the last character from the string and returns the character it removed.

Q&A

Q I want to iterate over a string and count the occurrences of the letter "t." How can I do this in Perl?
A Well, you could use a for loop and one of the string functions to work your way through the string one character at a time, but that would be a terrible amount of overkill (and expose you as a C programmer who still thinks of strings as null- terminated arrays). Perl's good with strings, and it has built-in mechanisms for finding stuff in strings so you don't have to do perverse character-by-character comparisons. You'll learn more about pattern matching on Day 9. Don't spend a lot of time iterating over strings until you read that.

Q Can I use printf just like I do in C?
A Well, you can, but you should really get used to working with print instead. The print function is more efficient, and helps cover up things like rounding-off errors in floating-point numbers. Its really a much better idea to use print for the vast majority of cases and only fall back on printf for specific reasons (like rounding).
If you do use printf, you can use all of the formatting codes you can in the C version of printf except for *.

Q Why is it important that some functions are functions and some functions are actually operators? Don't they all behave the same?
A Nope. Functions and operators behave slightly differently. Functions, for example, have a higher precedence. And arguments to an operator may be grouped based on precedence (giving you odd results) as well. In most cases, however, the difference between a function and an operator should not cause you to lay awake at night.

Workshop

The workshop provides quiz questions to help you solidify your understanding ofthe material covered and exercises to give you experience in using what you've learned.Try to understand the quiz and exercise answers before you go on to tomorrow's lesson.

Quiz

1. What's the difference between the postfix increment operator ($x++) and the prefix increment operator (++$x)?

2. What does operator precedence determine? How about associativity?

3. What is a file handle? Why do you need one?

4. Define standard input and output. What are they used for?

5. What does the chomp function do?

6. What are the differences between print, printf, and sprintf? When would you use each one?

7. What do the following operators do?

.**ne||*=

Exercises

1. Write a program that accepts any number of lines of any kind of input, ending with a Return or Enter (similarly to how the stats.pl program works). Return the numb er of lines that were entered.

2. BUG BUSTER: What's wrong with this bit of code?

while () { print `Enter a name: `; chomp ($input = <INPUT>); if ($input ne `') {   $names++;} else { last; }}
3. Write a program that accepts input as multiple words on different lines, and combines those words into a single string.

4. Write a program that takes a string and then centers it on the screen (assume an 80-character line, and that the string is less than 80 characters). Hint: the length function will give you the length in characters of a string.

Answers

Here are the answers to the workshop questions in the previous section.

Quiz Answers

1. The difference in prefix and postfix operators is when the variable reference is used and when its value is evaluated. Prefix operators increment the value before using it; postfix increments the variable afterward.

2. Operator precedence determines which parts of an expression are evaluated first given expressions that contain other expressions. Associativity determines the order in which operators that have the same precedence are evaluated.

3. A file handle is used to read data from or write data to a source or a destination, be it a file, the keyboard, the screen, or some other device. File handles provide a common way for Perl to handle input and output with all those things.

4. Standard input and output are generic input sources and output destinations (that is, not specifically from or to files). They are most commonly used to get input fr om the keyboard or to print it to the screen.

5. The chomp function removes the newline from the end of a string. If there is no newline on the end of the string, chomp does nothing.

6. The print function is the general way of printing output to the screen or to some other output destination. The printf function prints formatted strings to some output destination; sprintf formats a string, but then simply returns that formatted string value instead of printing it.

7. The answers are:

. concatenates strings
** creates exponential numbers
ne "not equals" for strings
|| logical OR (C-style)
*= Multiply and assign; same as $x = $x * $y

Exercise Answers

1. Here's one answer:
#!/usr/bin/perl -w$input = `'; # temporary input$lines = 0; # count of lineswhile () { print `Enter some text: `; chomp ($input = <STDIN>); if ($input ne `') {   $lines++;  } else { last; }}print "Total number of lines entered: $lines\n";
2. The file handle for standard input is STDIN, not INPUT.

3. Here's one answer:

#!/usr/bin/perl -w$input = `'; # temporary input$sent = `'; # final sentence;while () { print `Enter a word: `; chomp ($input = <STDIN>); if ($input ne `') {   $sent .= $input . ` `;  } else { last; }}print "Final sentence: $sent\n";
4. Here's one answer:
#!/usr/bin/perl -w$input = ""; # temporary input$space = 0; # space around$length = 0 ; # length of strin gprint `Enter some text: `;chomp ($input = <STDIN>);$length = length $input;$space = int((80 - $length) / 2);print ` ` x $space;print $input;print ` ` x $space . "\n";print `*' x 80;
Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(0)

2 Star

(0)

1 Star

(0)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)