#!/usr/bin/perl
#cookie_demo.pl

use CGI;
use CGI::Carp qw(fatalsToBrowser);

$cgi = new CGI;

#Read the input variables
$name = $cgi->param('name');
$request = $cgi->param('request');

#Read the cookie variable
$ID = $cgi->cookie('ID');


#Leave the cookie as read unless
#it's being set to a new value
#or cleared.
if ( $request =~ /Set/ ) {

	#Update the cookie with the new variable
	if ( $name ) {
		$ID_cookie = $cgi->cookie( -name => ID, -value => $name,
								-path => '/', -expires => '+1M' );
		$ID = $name;
	}

} elsif ( $request =~ /Clear/ ) {

	#Clear the cookie. Set it to "" and expire yesterday
	$ID_cookie = $cgi->cookie( -name => ID, -value => "",
							-path => '/', -expires => '-1d' );
	$ID = "";
}

#Print a new "Content type" header
#And set the cookie at the same time;
print $cgi->header( -cookie => $ID_cookie );

#substitute the results into the original form
open (FORM, "course/cgi_use/cookie_form.html")
	or die "Can't open cookie_form page: $!";

while ( <FORM> ) {
	
	#substitute the cookie value into the reserved place	
	s{<!-- cookie_results -->}{$ID};

	print;

}

close FORM;