O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.1. Input from STDIN

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required