Learning Perl on Win32 Systems

Learning Perl on Win32 SystemsSearch this book
Previous: 5.6 ExercisesChapter 6Next: 6.2 Input from the Diamond Operator

6. Basic I/O

Input from STDIN
Input from the Diamond Operator
Output to STDOUT

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> construct. Evaluating this in a scalar context gives the next line of input,[1] or undef if there are no more lines, like so:

[1] Up to a newline, or whatever you've set $/ to.

$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 this way.

Previous: 5.6 ExercisesLearning Perl on Win32 SystemsNext: 6.2 Input from the Diamond Operator
5.6 ExercisesBook Index6.2 Input from the Diamond Operator