Practical uses of while loops: taking input from STDIN

STDIN is the standard input stream for any Unix program. If a program is interactive, it will take input from the user via STDIN. Many Unix programs accept input from STDIN via pipes and redirection. For instance, the Unix cat utility prints out any file it has redirected to its STDIN:

% cat < hello.pl

Unix also has STDOUT (the standard output) and STDERR (where errors are printed to).

We can get a Perl script to take input from STDIN (standard input) and do things with it by using the line input operator, which is a set of angle brackets with the name of a filehandle in between them:

my $user_input = <STDIN>;

The above example takes a single line of input from STDIN. The input is terminated by the user hitting Enter. If we want to repeatedly take input from STDIN, we can use the line input operator in a while loop:

#!/usr/bin/perl -w

while ($_ = <STDIN>) {
        # do some stuff here, if you want...
        print;     # remember that print takes $_ as its default argument
]

Conveniently enough, the while statement can be written more succinctly, because in these circumstances, the line input operator assigns to $_ by default:

while (<STDIN>) {
        print;
}

Better yet, the default filehandle used by the line input operator is STDIN, so we can shorten the above example yet further:

while (<>) {
        print;
}

As always, there's more than one way to do it.

The above example script (which is available in your directory as exercises/cat.pl) will basically perform the same function as the Unix cat command; that is, print out whatever's given to it through STDIN.

Try running the script with no arguments. You'll have to type some stuff in, line by line, and type CTRL-D (a.k.a. ^D) when you're ready to stop. ^D indicates end-of-file (EOF) on most Unix systems.

Now try giving it a file by using the shell to redirect its own source code to it:

perl exercises/cat.pl < exercises/cat.pl

This should make it print out its own source code.