Reading from standard input (via the Perl filehandle called
STDIN
) is easy. We've been doing it already with the
<STDIN>
operation. Evaluating this in a scalar context gives the next line of input,[
1
] or
undef
if there are no more lines, like so:
$a = <STDIN>; # read the next line
[1] Up to a newline, or whatever you've set
$/
to.
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 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.
while (<STDIN>) { # like "while(defined($_ = <STDIN>)) {" chomp; # like "chomp($_)" # other operations with $_ here }
Since the
$_
variable is the default for many operations, you can save a noticeable amount of typing this way.