1.5.1 Reading a Single Value From the Terminal

The following program prints a prompt on the terminal asking the user to enter a Fahrenheit temperature. It converts the temperature to Celsius and prints the answer.

Program 1.6

#!/usr/bin/perl
#file fahrenheit2.pl
use strict;
my ($fahrenheit,$celsius);

print "Please enter a Fahrenheit temperature >> ";
$fahrenheit = ;
chomp ($fahrenheit);

$celsius = 5/9 * ($fahrenheit - 32);
printf "%4.0f degrees Fahrenheit is equal to %6.1f degrees Celsius.\n", 
    $fahrenheit, $celsius;

The line of code after variable declaration in the program is a print statement. Here printing is done on the userÕs terminal. The terminal is called STDIN for reading and STDOUT for writing. STDOUT stands for the standard output stream or filehandle. These are two names for the same thing for two purposes. The print statement can be rewritten with STDOUT as follows:

print STDOUT "Please enter a Fahrenheit temperature\n";

In general, the first Òargument" to print is a filehandle and if the filehandle is not provided, STDOUT is taken as the default. We use double quotes to indicate that it is not a real argument in the traditional sense because it is not followed by a comma.

The next statement in the program reads a line of input from the default filehandle.

fahrenheit = <STDIN>;

The left hand side of the assignment statement has a scalar variable. The right hand side reads from the STDIN filehandle. Because the left side is scalar, such a reading is said to take place in a scalar context. In a scalar context, <STDIN> reads the next input line and assigns it to the $fahrenheit variable.

When Perl reads, it reads the whole line of input, i.e., up to and including the first \n character. Thus, a line of input contains what is seen on the terminal followed by the newline character \n at the very end. This newline character is removed from the end of the input line by using the chomp operation. chomp is a built-in function that takes a string as its argument and removes the last character only if the last character is \n. If the last character is not \n, it is not removed. chomp is particularly useful for reading lines from the terminal. There is a related function called chop that takes a string argument and removes the last character no matter what it is.