#!/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


  # HTML output begins here
    print header;
    print "<title>Good Advice</title>";
    print "<h1>Good Advice</h1>";

  # truly dynamic generation
  #  output changes depending on input
    if ($action=~/Message (\d+)/) {         # untainting data
        my $message_no = $1 - 1;            # arrays begin at 0
        print '  <strong>', $advice[$message_no], '</strong>'; 
    }

  # this part is always present
    print "<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";
    print "</form>";
## End of example ##
