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, ...

Get Learning Perl, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.