Chapter 6. I/O Basics

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 a little more about those operations. As the title of this chapter implies, there will be more about Perl’s I/O operations in Chapter 11.

Input from Standard Input

Reading from the standard input stream is easy.[1] We’ve been doing it already with the <STDIN> operator.[2] 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.[3] 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 saw $_";
}

Now, to make this shortcut, Larry chose some useless syntax. That is, this is literally saying, “Read a line of input, and see if it’s true. (Normally it is.) And if it is true, enter the while loop, but throw away that line of input! ...

Get Learning Perl, 3rd 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.