Skip to Content
Learning Perl, 7th Edition
book

Learning Perl, 7th Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
October 2016
Beginner content levelBeginner
391 pages
10h 38m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 7th Edition

Chapter 5. Input and Output

You’ve already seen how to do some input/output (I/O) in order to make some of the earlier exercises possible. But now you’ll learn more about those operations by covering the 80% of the I/O you’ll need for most programs. If you’re already familiar with the workings of standard input, output, and error streams, you’re ahead of the game. If not, we’ll get you caught up by the end of this chapter. For now, just think of “standard input” as being “the keyboard,” and “standard output” as being “the display screen.”

Input from Standard Input

Reading from the standard input stream is easy. You’ve been doing it already with the <STDIN> operator. Evaluating this operator in a scalar context gives you the next line of input:

$line = <STDIN>;                # read the next line
chomp($line);                   # and chomp it

chomp($line = <STDIN>);         # same thing, more idiomatically

What we’re calling the line-input operator here, <STDIN>, is actually a line-input operator (represented by the angle brackets) around a filehandle. You’ll learn about filehandles later in this chapter.

Since the line-input operator will return undef when you reach end-of-file, this is handy for dropping out of loops:

while (defined($line = <STDIN>)) {
  print "I saw $line";
}

There’s a lot going on in that first line: you’re reading the input into a variable, checking that it’s defined, and if it is (meaning that we haven’t reached the end of the input) you’re running the body of the while loop. So, inside the body of the loop, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl One-Liners

Perl One-Liners

Peteris Krumins
Learning Perl, 8th Edition

Learning Perl, 8th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant

Publisher Resources

ISBN: 9781491954317Errata Page