#!/usr/bin/perl -Tw

#++
# Based on <URL:http://www.wiley.com/legacy/compbooks/stein/text/advice.txt>
#
# Source code to accompany 
#   _Official Guide to Programming with CGI.pm: The Standard for Building
#   Web Scripts_
#   by Lincoln Stein
#   (c) 1998 byLincoln Stein
#  Published by John Wiley & Sons, Inc.
#--

use CGI qw(:standard :Carp -debug);
use diagnostics; # verbose error messages
use strict;      # check for mistakes
$| = 1;          # flush output after each output statement
$\ = "\n";       # include \n at end of all output statements

  # initialize variables
   my @advice = (                           # hardcoded array
	   'A stitch in time saves nine.',
	   'Look both ways before crossing the street.',
	   'Chew completely before swallowing.',
	   'A penny saved is a penny earned.',
	   'Fools rush in where angels fear to tread.'
           );
   my $action  = param('action');           # field from HTML form
   my $maxmess = scalar(@advice) - 1;       # largest possible ...
                                            # value of $action ...
                                            # (arrays begin at zero)

  # HTML output begins here
    print header;                           # CGI.pm:standard gives ...
                                            # us the MIME-type header
    print "<title>Good Advice</title>";
    print "<h1>Good Advice</h1>";

  # truly dynamic generation
  #  output changes depending on input
    if ($action && ($action=~/Message (\d+)/)) { # untainting data

      # perl will let us do anything with $action now that it
      # is untainted.  But we still need to verify that it is 
      # valid

      my $message_no = $1 - 1;              # arrays begin at 0

      if ($maxmess >= $message_no && $message_no >= 0) {
        print '  <strong>', $advice[$message_no], '</strong>';
      } else {
        # $action was a number but it was not in the valid range
	print '  <p><strong>Don\'t taunt the form!</strong><br></p>';
      }
    }

  # this part is always present
    print "\n<form>";
    my $message;
    $\ = ""; # to stop the \n from being treated as a space in the HTML
    foreach $message (1..scalar(@advice)) { # scalar(@advice) is ...
                                            # ... # of elements in @advice
        print '  <input type="submit" name="action" value="Message ',
	      $message, '">' . "\n";
    }
    $\ = "\n";
    print "</form>";

    print "<!-- This document is *not* valid HTML -->"

## End of example ##
