Here is an awk program to convert between celcius and Fahrenheit temperatures.
Unlike most of my programs, this program is interactive. Once started, it interacts with the user at the command line, and accepts commands until the user quits.
Here is the run:
[513]-> cel_fahr
Current input set to: fahrenheit
enter q, f, c, or temp:
212
212 degrees F is 100 degrees C
Current input set to: fahrenheit
enter q, f, c, or temp:
rt
Current input set to: fahrenheit
enter q, f, c, or temp:
c
Current input set to: celcius
enter q, f, c, or temp:
0
0 degrees C is 32 degrees F
Current input set to: celcius
enter q, f, c, or temp:
q
In the run above, the user input is in black, while the displayed text is in green. Notice that when I type in a number, the system interprets it as either degrees C or F (depending on the input setting), and prints the conversion.
If I type "c" or "f", the input units are changed. If I type "q", the system quits. If I type anything else that is not a number (example "rt"), the program ignores it.
Here is the script:
nawk '
BEGIN {
f = "fahrenheit"
c = "celcius"
choice = f
while (x != "q")
{
print
print "Current input set to: "choice
print "enter q, f, c, or temp: "
"read x;echo $x"|getline x
close "read x;echo $x"
if (x == "f") choice = f
if (x == "c") choice = c
if (x ~ /^[0-9]*$/ || -1*x ~ /^[0-9]*$/)
{
if (choice == f)
print x" degrees F is "5/9 * (x - 32)" degrees C"
if (choice == c)
print x" degrees C is "x*9/5 + 32" degrees F"
}
}
}'
Let's analyze the script. First, this script is completely in a BEGIN section, so it is a procedural program. We set the default choice to be fahrenheit, and then loop until the user enters a "q".
In the loop, we start by printing the menu, and then use getline to create a shell process which reads from the keyboard into unix variable x and then echos unix variable x into getline, where it is assigned to x in the awk program.
We then close the process so that, the next time we run the process, it will do a fresh read.
If the input is either "f" or "c", we set the choice.
Then, if the input is either a positive or negative number, we convert it from the input units to the other unit, and display the result.
0 comments:
Post a Comment