5.2 Perl Introduction

Introduction

General

Variables

Variable Declarations
Scalar Variables
Arrays
Hashes

Statements

Operators

Numeric Operators
Boolean Operators
String Operators
Logical
Binary Operators
Assignment Operations

Subroutine

Some important variables

$0 -- program name
@ARGV -- command line arguments
%ENV -- current environment
@_ -- parameters when within a subroutine
$$ -- process id

Input/Output

print
files

hash functions

string manipulation

Other Useful functions

system('command") -- execute system commands.

Sample Perl CGI Script (with form data processing)

#!/usr/bin/perl

sub ParseFormData()
{
 my($namevalue, $name, $value);
 my(@arrGetString) = split(/&/, $ENV{'QUERY_STRING'});
 foreach $namevalue (@arrGetString)
 {
  ($name, $value) = split(/=/, $namevalue);
  $value =~ tr/+/ /;
  $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack("C",hex($1))/eg;
  $HTTP_GET_VARS{$name} = $value;
 }
 
 if ($ENV{'REQUEST_METHOD'} eq 'POST')
 {
  my($postString);
  read(STDIN, $postString, $ENV{'CONTENT_LENGTH'});
  my(@arrPostString) = split(/&/, $postString);
  foreach $namevalue (@arrPostString)
  {
   ($name, $value) = split(/=/, $namevalue);
   $value =~ tr/+/ /;
   $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack("C",hex($1))/eg;
   $HTTP_POST_VARS{$name} = $value;
  }
 }
}

#ParseFormData;
print "Content-Type: text/plain\n\n";
print "test\n\n";
ParseFormData;
foreach $key (keys %HTTP_POST_VARS)
{
 print "$key = $HTTP_POST_VARS{$key}\n";
}

Exercise

  1. Stores three strings "Toyota", "Honda", "Nissan" into an array. Then, use a for-loop to output each element into three different lines.
  2. Stores the following pairs ("John Wong",  "thwong@senecac.on.ca"), ("John Selmys", "jselmys@senecac.on.ca") into a hash. Use the foreach-loop to display each element in the hash.
  3. Write a simple CGI script that formats a HTML page with a statement of "Hello! World!".
  4. Write a simple CGI script that redirect to the CS department main page.

Last modified on January 6, 2002