Extended Example

A Virtual Clock

The current time is 03:32:13 PM Friday October 10 2008 .


Show: time day month day-of-month year
Time style: 12-hour 24-hour

This example uses the Perl 5.0 and the CGI.pm module. For more information about this particular technique for CGI development, see the documentation for the module, or the book Official Guide to Programming with CGI.pm, by Lincoln D. Stein (Wiley, 1998). The example is from the companion website, <http://www.wiley.com/ compbooks/ stein/source.html>.

The "Virtual Clock" web page can be produced by the following code:

#!/usr/bin/perl
#script: time4.pl

use CGI ':standard';
use POSIX 'strftime';

# print the HTTP header and the HTML document
print header,
    start_html('A Virtual Clock'), h1('A Virtual Clock');
print_time();
print_form();
print end_html;

# print out the time
sub print_time {
  my($format);
  if (param) {
	$format = (param('type') eq '12-hour') ? '%r ' : '%T ' if param('time');   
	$format .= '%d ' if param('day');
	$format .= '%B ' if param('month');
	$format .= '%A ' if param('day-of-month');
	$format .= '%Y ' if param('year');
  } else {
	$format = '%r %A %B %d %Y';
  }
  $current_time = strftime($format,localtime);
  print p("The current time is ",strong($current_time),".", hr);
}
# print the clock settings form
sub print_form {
  print start_form,
    p("Show: ",
      checkbox(-name=>'time',-checked=>1),
      checkbox(-name=>'day',-checked=>1),
      checkbox(-name=>'month',-checked=>1),
      checkbox(-name=>'day-of-month',-checked=>1),
      checkbox(-name=>'year',-checked=>1), br,
      "Time style: ",
      radio_group(-name=>'type',
                -values=>['12-hour','24-hour'])),
    p(reset(-name=>'Reset'),
      submit(-name=>'Set')),
    end_form;
}