perl by qingyunliuliu


    Turning on cgi processing in
• Cgi processing cabability is available in
  the apache server but needs to be turned
  on by editing config files.
• Cgi processing handles requests to the
  server that have url:
     Turning on cgi processing in
•  Useful link:
• Activating CGI
• Using Notepad (or other text editor) open
   E:\Apache2\conf\httpd.conf (also should be
   start-menu shortcut called "Edit Apache HTTP
   httpd.conf File") and search for Options
   Indexes FollowSymLinks (about line 267)
   when you find it add ExecCGI to the end so it
   looks like
Options Indexes FollowSymLinks ExecCGI
       Turning on cgi processing in
• Enabling CGI in any directory [optional]
• If you want to use CGI outside ScriptAliased directory (ScriptAlias is
  usually the Apache2/cgi-bin/), you will need to uncomment the
  following line:
#AddHandler cgi-script .cgi
• becomes
AddHandler cgi-script .cgi .pl .rb
• (remove the #) I also added .pl behind .cgi so files with the 'perl'
  extension are also treated as cgi files.
  We’ll later use ruby, too so you might as well add rb extensions to
  the list.
  You might also want to comment out:
ScriptAlias /cgi-bin/ "E:/Apache2/cgi-bin/"
• so it becomes
#ScriptAlias /cgi-bin/ "E:/Apache2/cgi-bin/"
              Another useful page
•   There are just a few changes to make:
•   To find perl scripts in cgi-bin directory (fix path, too):
•   ScriptAlias /cgi-bin/ "C:/Program Files/Apache
•   To allow both pl and cgi suffix:
•   AddHandler cgi-script .cgi .pl .rb
•   <Directory />
     Options FollowSymLinks
     AllowOverride None
•   Change options to:
•   Options FollowSymLinks +ExecCGI
 On my apache version: about line
     187 of the httpdconf file
<Directory />
   Options FollowSymLinks ExecCGI
   AllowOverride None
   Order deny,allow
   Deny from all
                                   Turn on cgi
•   Enabling SSI [optional]
•   Find the line from Step 1: Activating CGI and add Includes to the end so it becomes Options
    Indexes FollowSymLinks ExecCGI Includes
    Find and uncomment the following lines #AddType text/html .shtml and #AddOutputFilter
    INCLUDES .shtml (Search for them, then remove the #)
    Some notes If you don't know what SSI (Server Side Include) is, I suggest looking for more info
    about it. It is a huge time saver for updating pages (you can update one "menu file" and have
    hundreds of pages reflect the updated changes). However, it adds additional strain on a server
    and can potentially make a server slightly less secure, so if you are not using, do not enable it.
    Since I use SSI for everything, I changed the settings so *.html files can also run SSI (by default
    it's only .shtml). So I have AddOutputFilter INCLUDES .shtml .html
    AddOutputFilter is completely different than the AddHandler server-parsed way Apache 1.3.x
    handled it.
•   Finding your location to perl
•   If you do not know where your perl.exe installed to, go to Start -> Search and type in a search for
    perl.exe This location is the path to perl you put on the top of all your cgi scripts. If you listened to
    my advice in the "Install" step, the path should be close to: E:/usr/bin/perl
                 Turning on cgi (unix)
•   Some notes For the perl path E:/usr/bin/perl.exe all of these are/were valid. I prefer
    the last one, but to each their own.
•   Note: for us this path will be something like
•   #!P:\perl\perl.exe
•   Testing CGIIf you did not disable ScriptAlias /cgi-bin/ then create a file in
    E:/Apache2/cgi-bin/ called hello.cgi and put these three lines in it (if you did disable
    it, put the CGI file anywhere in your document_root):
          print "Content-type:text/html\n\n";
          print "hello world";
•   Restart Apache if it is already running. Now go to or
    localhost and run this script. (scripts in Apache2/cgi-bin/ are read as by default, although if did step (2) you should be able to run
    CGI scripts from anywhere).
•   If you get a hello world in your browser, CGI is running. If you get a 500 error, go to
    the last entry in E:/Apache2/logs/error.log (or the Review Error Log in the start menu)
    to see exactly what caused this error.
          Port number 80 or 8080
         (line 53 in my httpd.conf)
# Listen: Allows you to bind Apache to specific IP
   addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
# Change this to Listen on specific IP addresses as shown
   below to
# prevent Apache from glomming onto all bound IP
   addresses (
Listen 80
       Addhandler (line 418)
• add .pl to this line:
AddHandler cgi-script .cgi .pl
  Some perl program examples
• Perl programs will need their first line to
  include the path to the perl compiler. This
  line starts with #! (called shebang)

Perl statements end in a semi-colon
 Hello world: note shebang 1st line points to
               perl on system
print "Content-type:text/html\n\n";
print "hello world";
Deploying the helloworld example:
   Drop perlscripts into cgi-bin
            Using variables
• Simple variables in perl start with a $:
$mystring = "Hello, World";
$mypi = "3.14159";
Note, there is no difference between string,
  int and float value declaration or
                   Using variables
print "Content-type: text/html \n\n"; # the header
$mystring = "Hello, World";
$myescapechar = "Welcome to Joe\'s";
$myinteger = "5";
$myinteger2 = "-5";
$mypi = "3.14159";
print $mystring;
print "<br />";
print $myescapechar;
print "<br />";
print $myinteger; print "<br />";
print $myinteger2; print "<br />";
print $mypi;
      Shortcut operators as in java or c++

print "content-type: text/html \n\n"; #The header
$x = 14;
$y = 10;
$area = ($x * $y);
print $area;
print "<br />";
$x += 4; #adds 4 to x
$y += 12; #adds 12 to y
$area = ($x * $y);
print $area;
Running vars2
print "content-type: text/html \n\n"; #The header
$single = "This string is single quoted";
$double = 'This string is double quoted';
$userdefined = q^Carrot is now our quote^;
print $single;
print " ";
print $double;
print " ";
print $userdefined;
Running it
print "content-type: text/html \n\n"; #The header
$mystring = "Welcome to higgins perl examples!";
$twoarguments = substr($mystring, 11);
$threearguments = substr($mystring, 8, 2);
print $twoarguments;
print "<br />";
print $threearguments;
             More substrings
print "content-type: text/html \n\n"; #The header
$mystring = "Welcome to!";
print $mystring;
print "";
substr($mystring, 11) = "!";
print $mystring;
  Escape char to print $ and @
#since $ is used to define a var and @ defines an array
#we need to use escape chars to put these in our output
print "Content-type: text/html \n\n"; # the header
$string = "David paid \$4.34 for Larry\'s shirt.";
$email = "youremail\";
print "$string<br />";
print "$email<br />";
print '$string and $email';
Substrings continued
Interpolation: interpreting variables
          and instructions

print "Content-type:text/html\n\n";
$a = 'apples';
$b = 'pears';
print "$a and $b";
   From the previous example
$a = 'apples';
$b = 'pears';
print "$a and $b";

• In the previous example, note that perl
  “interpreted” variable references even
  though they were inside the quotes and
  replaced the $a and $b by their values.
         Fibonacci numbers
print "$next \n";
print "$next \n";
#print "$next \n";
                          Fib program
            Arrays in perl
• Use @ to denote an array. Note recursive
  reference in the 2nd line below:
@music = ("whistle", "flute");
@moremusic = ("organ", @music, "harp");
@food = ("apples", "pears", "eels");
       Array example –some recursive
      assignments, push and pop, output
print "Content-type:text/html\n\n";
@music = ("whistle", "flute");
@moremusic = ("organ", @music, "harp");
@food = ("apples", "pears", "eels");
push(@food, "eggs");
push(@food, ("eggs", "lard"));
$grub = pop(@food);
($a, $b) = @food;
print @food; # By itself
print "@food";         # Embedded in double quotes
print @food."";        # In a scalar context
Has output
                         A hash
• A hash is a key-value pair structure
• It is designated with a % symbol
%coins = ( "Quarter" , '25',"Dime" , '10',"Nickel", '05', );
                    Hash “table”
print "content-type: text/html \n\n"; #The header
%coins = ( "Quarter" , '25',"Dime" , '10',"Nickel", '05', );
while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
$coins{Penny} = "01";
$coins{HalfDollar} = "50";
print "<br />"; while (($key, $value) = each(%coins)){
print $key.", ".$value."<br />";
 Running CGI…an html points to a cgi program
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"

<!-- reply.html
    A trivial document to call a simple Perl CGI program
<html xmlns = "">
   <title> XHTML to call the Perl CGI program, reply.cgi
     This is our first Perl CGI example
     <br /><br />
     <a href = "http://localhost/cgi-bin/reply.cgi">
     Click here to run the CGI program, reply.cgi
Reply.cgi in the cgi-bin directory
# reply.cgi
# This CGI program returns a greeting to the client
print "Content-type: text/html \n\n",
"<?xml version = '1.0' encoding = 'utf-8'?> \n",
"<html xmlns = ''>\n",
"<head><title> reply.cgi example </title></head>\n",
"<h1> Greetings from your Web server! </h1>\n",
The html
The reply uses CGI module
• Use ppm to install the CGI module:
C:\PERL>ppm install CGI

• (See screenshot in next slide)
                          ppm install CGI
•   C:\PERL>ppm install CGI
•   ====================
•   Install 'CGI' version 2.91 in ActivePerl
•   ====================
•   Installing C:\Perl\html\site\lib\CGI.html
•   Installing C:\Perl\html\site\lib\CGI\Apache.html
•   Installing C:\Perl\html\site\lib\CGI\Carp.html
•   Installing C:\Perl\html\site\lib\CGI\Cookie.html
•   Installing C:\Perl\html\site\lib\CGI\Fast.html
•   Installing C:\Perl\html\site\lib\CGI\Pretty.html
•   Installing C:\Perl\html\site\lib\CGI\Push.html
•   Installing C:\Perl\html\site\lib\CGI\Switch.html
•   Installing C:\Perl\html\site\lib\CGI\Util.html
•   Installing C:\Perl\site\lib\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Installing C:\Perl\site\lib\CGI\
•   Successfully installed CGI version 2.91 in ActivePerl uses CGI module
#print "Content-type:text/html\n\n";
# A CGI program, written using, to process
# the popcorn sales form
# Initialize total price and total number of purchased items
$total_price = 0;
$total_items = 0;
use CGI ":standard";
# First produce the header part of the HTML return value
print header();
print start_html("CGI-Perl Popcorn Sales Form, using");
# Set local variables to the parameter values
my($name, $street, $city, $payment) =
      (param("name"), param("street"),
      param("city"), param("payment"));
my($unpop, $caramel, $caramelnut, $toffeynut) =
      (param("unpop"), param("caramel"),
       param("caramelnut"), param("toffeynut"));
# Compute the number of items ordered and the total cost
if ($unpop > 0) {
    $cost = 3.0 * $unpop;
    $total_price += $cost;
    $total_items += $unpop;
if ($caramel > 0) {
    $cost = 3.5 * $caramel;
    $total_price += $cost;
    $total_items += $caramel;
if ($caramelnut > 0) {
    $cost = 4.5 * $caramelnut;
    $total_price += $cost;
    $total_items += $caramelnut;
if ($toffeynut > 0) {
    $cost = 5.0 * $toffeynut;
    $total_price += $cost;
    $total_items += $toffeynut;
# Produce the result information to the browser and finish the page
print "<h3>Customer:</h3>\n",
     "$name <br/>\n", "$street <br/>\n", "$city <br/>\n",
     "Payment method: $payment <br/><br/>\n",
     "<h3>Items ordered:</h3> \n",
     "Unpopped popcorn: $unpop <br/> \n",
     "Caramel popcorn: $caramel <br/> \n",
     "Caramel nut popcorn: $caramelnut <br/> \n",
     "Toffey nut popcorn: $toffeynut <br/><br/> \n",
     "You ordered $total_items popcorn items <br/>\n",
     "Your total bill is: \$ $total_price <br> \n";
print end_html();
Html Form in htdocs takes an order
Script (in cgi-bin) processes it
Cookies: prints “first visit” or…
# - A CGI-Perl program to use a cookie to remember the
# day of the last login from a user and display it when run
use CGI ":standard";
# Get the existing day cookie, if there was one

@last_day = cookie('last_time');

# Get the current date and make the new cookie

$day_of_week = (qw(Sunday Monday Tuesday Wednesday Thursday
           Friday Saturday)) [(localtime)[6]];
$month = (qw(January February March April May June July
     August September October November December))
$day_of_month = (localtime)[3];
@day_stuff = ($day_of_week, $day_of_month, $month);

$day_cookie = cookie(-name => 'last_time',
            -value => \@day_stuff,
            -expires => '+5d');
# Produce the return document
# First, put the cookie in the new header
print header(-cookie => $day_cookie);
print start_html('This is');
# If there was no day cookie, this is the first visit
if (scalar(@last_day) == 0) {
    print "Welcome to you on your first visit to our site <br />";
# Otherwise, welcome the user back and give the date of the
# last visit
else {
    ($day_of_week, $day_of_month, $month) = @last_day;
    print "Welcome back! <br /> ",
        "Your last visit was on ",
        "$day_of_week, $month $day_of_month <br />";
print end_html;
  File i/o: processing a data file
Names that end in 'son'


Percent of employees under 40 is: 20
Average salary of employees under 40 is: 35000
There were no employees under 40 who earnedover

# - An example program to illustrate some of the
#        features of Perl
# Input: A file of lines of employee data, where each line has
#     name:age:department code:salary
# Output: 1. The names of all employees whose names end with "son"
#     2. Percentage of employees under 40 years old
#     3. Average salary of employees under 40 years old
#     4. An alphabetical list of employees who are under 40
#        years old and who have salaries more than $40,000
# Open the data file and display a header for employees
# whose names end in 'son'

open(EMPLOYEES, "employees.txt") || die "Can't open employees $!";
print "Names that end in 'son'\n\n";
# Loop to read and process the employee data
while (<EMPLOYEES>) {
# Increment the number of employees and chop off the newline

# Split the input line into its four parts
  ($name, $age, $dept, $salary) = split(/:/);
# If the name ends in 'son', print the name
   if ($name =~ /son$/) {
       print "$name \n";
# If the employee is under 40, count him or her and add his or her
# salary to the sum of such salaries
   if ($age < 40) {
       $salary_sum += $salary;
# If the salary was over 40,000, add the person and his or her
# salary to the hash of such people

     if ($salary > 40000) {
         $sublist{$name} = $salary;
# If there was at least one employee, continue
if ($total_employees > 0) {
# If there was at least one under 40, continue
      if ($under_40 > 0) {
# Compute and display the % of employees under 40 and their
# average salaries
$percent = 100 * $under_40 / $total_employees;
        print "\nPercent of employees under 40 is: $percent \n";
        $avg = $salary_sum / $under_40;
        print "Average salary of employees under 40 is: $avg \n";
# If there was at least one under 40 who earned a salary > 40,000,
# continue
       if (keys(%sublist)) {
# Sort and display the names of the employees under 40 with
# with salaries > 40,000

       print "Sorted list of employees under 40",
           " with salaries > \$40,000 \n";
       @sorted_names = sort (keys(%sublist));
       print "\nName \t\t Salary\n";
       foreach $name (@sorted_names) {
          print "$name \t \$$sublist{$name} \n";
     else {
        print "There were no employees under 40 who earned";
        print "over $40,000 \n";
     } #** of if (keys(%sublist))
  else {
     print "There were no employees under 40 \n";
  } #** of if ($under_40 > 0)
else {
   print "There were no employees\n";
} #** of if ($total_employees > 0)
               Data file

To top