5.3. Reading from STDIN
The three filehandles STDIN, STDOUT, and STDERR, as you may recall, are names given to three predefined streams, stdin, stdout, and stderr. By default, these filehandles are associated with your terminal. When printing output to the terminal screen, STDOUT is used. When printing errors, STDERR is used. When assigning user input to a variable, STDIN is used.
The Perl <> input operator encloses the STDIN filehandle so that the next line of standard input can be read from the terminal keyboard and assigned to a variable. Unlike the shell and C operations for reading input, Perl retains the newline on the end of the string when reading a line from standard input. If you don't want the newline, then you have to explicitly remove it, or "chomp" it off (see "The chop and chomp Functions" on page page 95).
5.3.1. Assigning Input to a Scalar Variable
When reading input from the filehandle STDIN, if the context is scalar, one line of input is read, including the newline, and assigned to a scalar variable as a single string.
Example 5.25.
(The Script)
# Getting a line of input from the keyboard.
1 print "What is your name? ";
2 $name = <STDIN>;
3 print "What is your father's name? ";
4 $paname=<>;
5 print "Hello respected one, $paname";
(Output)
1 What is your name? Isabel
3 What is your father's name? Nick
5 Hello respected one, Nick
The string What is your name? is sent to STDOUT, which is the screen by default. The input operator <> (called the diamond operator) surrounding STDIN reads one line of input and assigns that line and its trailing newline to the scalar variable $name. When input is assigned to a scalar, characters are read until the user presses the Enter key. The string is printed to STDOUT. If the input operator is empty, the next line of input is read from STDIN, and the behavior is identical to line 2, except input is assigned to $paname.
|
5.3.2. The chop and chomp Functions
The chop function removes the last character in a scalar variable and the last character of each word in an array. Its return value is the character it chopped. Chop is used primarily to remove the newline from the line of input coming into your program, whether it is STDIN, a file, or the result of command substitution. When you first start learning Perl, the trailing newline can be a real pain!
The chomp function was introduced in Perl 5 to remove the last character in a scalar variable and the last character of each word in an array only if that character is the newline (or, to be more precise, the character that represents the input line separator, initially defined as a newline and stored in the $/ variable). It returns the number of characters it chomped. Using chomp instead of chop protects you from inadvertently removing some character other than the newline.
Example 5.26.
(The Script)
# Getting rid of the trailing newline. Use chomp instead of chop.
1 print "Hello there, and what is your name? ";
2 $name = <STDIN>;
3 print "$name is a very high class name.\n";
4 chop($name); # Removes the last character no matter what it is.
5 print "$name is a very high class name.\n\n";
6 chop($name);
7 print "$name has been chopped a little too much.\n";
8 print "What is your age? ";
9 chomp($age=<STDIN>); # Removes the last character if
# it is the newline.
10 chomp($age); # The last character is not removed
# unless a newline.
11 print "For $age, you look so young!\n";
(Output)
1 Hello there, and what is your name? Joe Smith
3 Joe Smith
is a very high class name.
5 Joe Smith is a very high class name.
7 Joe Smit has been chopped a little too much.
8 What is your age? 25
11 For 25, you look so young!
1 | The quoted string is printed to the screen, STDOUT, by default. | 2 | The scalar variable is assigned a single line of text typed in by the user. The <> operator is used for read operations. In this case, it reads from STDIN, which is your keyboard, until the carriage return is pressed. The newline is included in the text that is assigned to the variable $name. | 3 | The value of $name is printed. Note that the newline breaks the line after Joe Smith, the user's input. | 4 | The chop function removes the last character of the string assigned to $name. The character that was chopped is returned. | 5 | The string is printed again after the chop operation. The last character was removed (in this case, the newline). | 6 | This time chop will remove the last character in Joe Smith's name; i.e., the h in Smith. | 7 | The quoted string is printed to STDOUT, indicating that the last character was removed. | 9 | The user input is first assigned to the variable $age. The trailing newline is chomped. The character whose value is stored in the special variable, $/, is removed. This value is by default the newline character. The number of characters chomped is returned. Because of the low precedence of the equal (=) operator, parentheses ensure that the assignment occurs before the chomp function chomps. | 10 | The second chomp will have no effect. The newline has already been removed, and chomp removes only the newline. It's safer than using chop. | 11 | The chomped variable string is printed. |
|
5.3.3. The read Function
The read function allows you to read a number of bytes into a variable from a specified filehandle. If reading from standard input, the filehandle is STDIN. The read function returns the number of bytes that were read.
number_of_bytes = read(FILEHANDLE,buffer,how_many_bytes);
Example 5.27.
(The Script)
# Reading input in a requested number of bytes
1 print "Describe your favorite food in 10 bytes or less.\n";
print "If you type less than 10 characters, press Ctrl-d on a line
by itself.\n";
2 $number=read(STDIN, $favorite, 10);
3 print "You just typed: $favorite\n";
4 print "The number of bytes read was $number.\n";
(Output)
1 Describe your favorite food in 10 bytes or less.
If you type less than 10 characters, press Ctrl-d on a line by
itself.
apple pie and ice cream <-user input
3 You just typed: apple pie
4 The number of bytes read was 10.
The user is asked for input. If he types less than 10 characters, he should press <Ctrl>-d to exit. The read function takes three arguments: the first argument is STDIN, the place from where the input is coming; the second argument is the scalar $favorite, where the input will be stored; and the third argument is the number of characters (bytes) that will be read. The 10 characters read in are printed. The rest of the characters were discarded. The number of characters (bytes) actually read was stored in $number and is printed.
|
|
5.3.4. The getc Function
The getc function gets a single character from the keyboard or from a file. At EOF, getc returns a null string.
getc(FILEHANDLE)
getc FILEHANDLE
getc
Example 5.28.
(The Script)
# Getting only one character of input
print "Answer y or n ";
1 $answer=getc; # Gets one character from stdin
2 $restofit=<>; # What remains in the input buffer is
# assigned to $restofit
3 print "$answer\n";
4 print "The characters left in the input buffer were:
$restofit\n";
(Output)
1 Answer y or n yessirreebob <ENTER>
3 y
4 The characters left in the input buffer were: essirreebob
Only one character is read from the input buffer by getc and stored in the scalar $answer. The characters remaining in the input buffer are stored in $restofit. This clears the input buffer. Now, if you ask for input later in the program, you will not be picking up those characters that were left hanging around in the buffer. The character that was read in by getc is printed. The characters stored in $restofit are displayed.
|
|
5.3.5. Assigning Input to an Array
When reading input from the filehandle STDIN, if the context is an array, then each line is read with its newline and is treated as a single list item, and the read is continued until you press <Ctrl>-d (in UNIX) or <Ctrl>-z (in Windows) for end of file (EOF). Normally, you will not assign input to an array, because it could eat up a large amount of memory, or because the user of your program may not realize that he should press <Ctrl>-d or <Ctrl>-z to stop reading input.
Example 5.29.
(The Script)
# Assigning input to an array
1 print "Tell me everything about yourself.\n ";
2 @all = <STDIN>;
3 print "@all";
4 print "The number of elements in the array are: ",
$#all + 1, ".\n";
5 print "The first element of the array is: $all[0]";
(Output)
1 Tell me everything about yourself.
2 OK. Let's see I was born before computers.
I grew up in the 50s.
I was in the hippie generation.
I'm starting to get bored with talking about myself.
<Ctrl>-d
3 OK. Let's see I was born before computers.
I grew up in the 50s.
I was in the hippie generation.
I'm starting to get bored with talking about myself.
4 The number of elements in the array are: 4.
5 The first element of the array is:
OK. Let's see I was born before computers.
The string Tell me everything about yourself. is printed to STDOUT. The input operator <> surrounding STDIN reads input lines until <Ctrl>-d, EOF, is reached. (For Windows users, use <Ctrl>-z instead of <Ctrl>-d.) Each line and its trailing newline are stored as a list element of the array @all. The user input is printed to the screen after the user presses <Ctrl>-d or <Ctrl>-z. The $# construct lets you get the last subscript or index value in the array. By adding 1 to $#all, the size of the array is obtained; i.e., the number of lines that were read. $all[0] is the first element of the array that evaluates to the first line of input from the user. Each line read is an element of the array.
|
5.3.6. Assigning Input to a Hash
Example 5.30.
(The Script)
# Assign input to a hash
1 $course_number=101;
2 print "What is the name of course 101?";
3 chomp($course{$course_number} = <STDIN>);
4 print %course, "\n";
(Output)
2 What is the name of course 101? Linux Administration
4 101Linux Administration
The scalar variable $course_number is assigned the value 101. The string What is the name of course 101? is printed to STDOUT. The name of the hash is %course. We are assigning a value to one of the hash elements. The key is $course_number enclosed in curly braces. The chomp function will remove the newline from the value assigned by the user. The new array is printed. It has one key and one value.
|