#!/usr/bin/perl # ################################################################# # # Project: CGI-Programming # # Filename: calculator.cgi # # Version: 1.0 # # Autor: Akadia AG, Christoph Gaechter 26.12.1999 # # Purpose: Shows how to implement a simple form to # perform an operation with two numbers # # ################################################################# # use strict; # enforce variable declarations and quoting use CGI qw(:standard); # load CGI module use CGI::Carp qw(fatalsToBrowser carpout); # Error Messages to Browser my ($n1,$n2,$n3,$op,$exp,$msg); print header(), start_html("Calculator"); print ("\n"); print h1("Calculator @ $ENV{SERVER_NAME}"); # Check for valid input if (param()) { $n1 = param('number1'); $n2 = param('number2'); $op = param('operation'); if (! $n1) { $msg = "Invalid first number, try again!"; } elsif (! $n2) { $msg = "Invalid second number, try again!"; } # Calculate the apropriate expression if (! $msg) { if ($op eq 'add') { $n3 = $n1 + $n2; $exp = "$n1 + $n2"; } elsif ($op eq 'sub') { $n3 = $n1 - $n2; $exp = "$n1 - $n2"; } elsif ($op eq 'mul') { $n3 = $n1 * $n2; $exp = "$n1 * $n2"; } elsif ($op eq 'div') { $n3 = $n1 / $n2; $exp = "$n1 / $n2"; } else { $msg = "Unknown operation, try again!"; } } } # Create HTML Form with results if ($msg) { print hr(); print ("
Error occured: $msg
\n"); } else { print hr(), start_form(); print ("First number | \n"); print ("\n"); print (" |
---|---|
Second number | \n"); print ("\n"); print (" |
Operation | \n"); print ("\n");
# Dynamicly create the radio buttons (checked / unchecked)
$msg = "input type='radio' name='operation' value='add' ";
if (! $op or $op eq 'add') {
print ("<$msg checked>\n");
} else {
print ("<$msg>\n");
}
print ("Addition\n");
print (" \n"); $msg = "input type=radio name='operation' value='sub' "; if ($op eq 'sub') { print ("<$msg checked>\n"); } else { print ("<$msg>\n"); } print ("Subtraction\n"); print (" \n"); $msg = "input type=radio name='operation' value='mul' "; if ($op eq 'mul') { print ("<$msg checked>\n"); } else { print ("<$msg>\n"); } print ("Multiplication\n"); print (" \n"); $msg = "input type=radio name='operation' value='div' "; if ($op eq 'div') { print ("<$msg checked>\n"); } else { print ("<$msg>\n"); } print ("Division\n"); print (" |
  | \n"); print ("|
Expression | \n"); print ("$exp | \n"); print ("
Result | \n"); print ("$n3 | \n"); print ("
  | \n"); print ("|
\n"); print (" | Show source\n"); print (" |