Chapter 5. Input and Output

We’ve already seen how to do some input/output (I/O) in order to make some of the earlier exercises possible. But now we’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. We’ve been doing it already with the <STDIN> operator.[13] 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

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: we’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) we’re running the body of the while loop. So, inside the body of the loop, we’ll see each line, one after another, in $line.[*] This is something you’ll want to do fairly often, so naturally Perl has a shortcut for it. The shortcut looks like this:

while (<STDIN>) { print "I ...

Get Learning Perl, 5th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.