28.3. Perl Examples

This section demonstrates a few examples of how Perl can be used for CGI. The examples show how you can leverage Perl's capabilities and add-on modules to deliver dynamic document content.

28.3.1. Date and Time Handling

When using Perl you have a ton of modules and libraries available to extend the language to interact with a variety of technologies and to perform a variety of calculations. One important and often-used segment of the libraries is time and date handling. This example shows a simple use of the extensive Time::Piece library.

For a more dynamic calendar example, see Example 3 in this chapter.

Example 1: A Simple Calendar

Source — Perl-Example01.cgi

#!/usr/bin/perl

# Use the Time::Piece library for our date/time needs
use Time::Piece;

# Set up the variables (today, month, year)
#  today = m/d/y
sub setvars() {

  # Default is today
  my $day = localtime->mday();
  my $month = localtime->mon();
  my $year = localtime->year();
  my $today = $month."/".$day."/".$year;

  # Return vars in a hash
  my %t = ("today" => $today,
            "month" => $month,
            "year" => $year);
  return %t;
}  # End setvars()


# Do the document header
sub docheader($$) {

  my $month = shift;
  my $year = shift;

my $t = Time::Piece->strptime($month,"%m");
$month_text = $t->strftime("%B");
# Print the document header (up to first date row) print <<HTML; Content-type: text/html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml1.dtd"> <html> <head> <title>Calendar - $month_text ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.