Chapter 5. Input and Output
We’ve seen how to do some input/output (I/O) to make some of the earlier exercises possible. 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 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, 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 with the <STDIN>
operator.[113] 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
.[114] 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, ...
Get Learning Perl, Fourth 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.