#!/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 ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("\n"); print ("
\n"); print ("
First number
Second number
Operation\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 ("
 
Expression $exp
Result $n3
 
Show source\n"); print ("

\n"); print end_form(); } # Build page footer print hr(); print ("$ENV{SERVER_SIGNATURE}\n"); print end_html();