Chapter 6. Basic I/O
Input from STDIN
Reading from standard input (via the Perl
filehandle called STDIN
) is easy. We’ve been
doing it already with the
<STDIN>
construct. Evaluating this in a scalar context gives the next line of
input,[46] or
undef
if there are no more lines, like so:
$a = <STDIN>; # read the next line
Evaluating in a list context produces all remaining lines as a list: each element is one line, including its terminating newline. We’ve seen this before, but as a refresher, it might look something like this:
@a = <STDIN>;
Typically, one thing you want to do is read all lines one at a time and do something with each line. One common way to do this is:
while (defined($line_ = <STDIN>)) { # process $line here }
As long as a line has been read in, <STDIN>
evaluates to a defined value, so the loop continues to execute. When
<STDIN>
has no more lines to read, it
returns undef
, terminating the loop.
Reading a scalar value from <STDIN>
into
$_
and using that value as the controlling
expression of a loop (as in the previous example) occurs frequently
enough so that Perl has an abbreviation for it. Whenever a loop test
consists solely of the input operator (something like
<...>
), Perl automatically copies the line
that is read into the
$_
variable.
For example:
while (<STDIN>) { # like "while(defined($_ = <STDIN>_)" chomp; # like "chomp($_)" # other operations with $_ here }
Because the $_
variable is the default for many operations, you can save a noticeable amount of typing ...
Get Learning Perl on Win32 Systems 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.