Chapter 4. Handling Files in Perl
IO Introduction > STDOUT > Writing Files > STDIN > Reading Files >
Reading Directories > Editing Files > Recursive Editing
Reading Information from Standard Input
When you want to get information into your program, how can you do it? The counterpart to the standard output destination, is the standard input source of data. Standard input is abbreviated to STDIN.
Normally, STDIN reads input from keys typed at the keyboard, but STDIN input doesn't always have to come from the keyboard. You can redirect STDIN to take its data from a selected file, and this can be done outside your program. To redirect STDIN to read from another file, you can use the "input redirection" operator, "<". So you could write:
perl perltest.pl < input.txt
You can even combine input and output redirection:
perl perltest.pl < input.txt > output.txt
Keep in mind, this redirection is performed by the operating system, not by Perl specifically. However, it works in Perl because Perl supports the functioning of STDIN instead of hardwiring input to the keyboard.
When you want to read from STDIN within your program, you can get a line of input by using the diamond operator, "<>". The diamond operator means "read a line of input". To read a line of input from STDIN and save the input in a variable, write:
$input = <STDIN>;
or, equivalently just:
$input = <>;
since it will read from STDIN by default. Don't put a space in between the brackets or it won't work.
Note that this will read a whole line of input including the newline (\n) character added on to the end when you hit the Enter key. Often you'll want to get rid of this \n character. To do that you can write:
Recall that chomp is the safe form of chop.
The next section will show you how to read from specific files, instead of from standard input.
Email me your comments!