0% found this document useful (0 votes)
60 views24 pages

Perl - Part Iv: Indian Institute of Technology Kharagpur

This document provides an overview of using Perl for CGI scripting. It defines associative arrays and hashes in Perl with examples. It discusses defining and calling subroutines, including passing arguments and using local variables. It provides examples of parsing form input and sending mail using CGI scripts in Perl. Key functions from the CGI.pm module are also introduced for generating HTML headers and decoding form values.

Uploaded by

Abdul Ghani Khan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views24 pages

Perl - Part Iv: Indian Institute of Technology Kharagpur

This document provides an overview of using Perl for CGI scripting. It defines associative arrays and hashes in Perl with examples. It discusses defining and calling subroutines, including passing arguments and using local variables. It provides examples of parsing form input and sending mail using CGI scripts in Perl. Key functions from the CGI.pm module are also introduced for generating HTML headers and decoding form values.

Uploaded by

Abdul Ghani Khan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Indian Institute of Technology Kharagpur

PERL – Part IV

Prof. Indranil Sen Gupta


Dept. of Computer Science & Engg.
I.I.T. Kharagpur, INDIA

Lecture 24: PERL – Part IV


On completion, the student will be able to:
1. Define associative arrays in Perl, with examples.
2. Define subroutines, and specify local variables.
3. Demonstrate the coding of CGI script programs in
Perl.
4. Demonstrate the coding of CGI script programs in
other languages like shell scripts, and C.
5. Conceive the security issues in CGI scripts.

1
Associative Arrays

Introduction

• Associative arrays, also known as


hashes.
¾Similar to a list
ƒ Every list element consists of a pair, a hash key
and a value.
ƒ Hash keys must be unique.
¾Accessing an element
ƒ Unlike an array, an element value can be found
out by specifying the hash key value.
ƒ Associative search.
¾A hash array name must begin with a ‘%’.

2
Specifying Hash Array

• Two ways to specify:


¾Specifying hash keys and values, in proper
sequence.
%directory = (
“Rabi”, “258345”,
“Chandan”, “325129”,
“Atul”, “445287”,
“Sruti”, “237221”
);

¾Using the => operator.


%directory = (
Rabi => “258345”,
Chandan => “325129”,
Atul => “445287”,
Sruti => “237221”
);
ƒ Whatever appears on the left hand side of
‘=>’ is treated as a double-quoted string.

3
Conversion Array <=> Hash

• An array can be converted to hash.


@list = qw (Rabi 258345 Chandan 325129 Atul
445287 Sruti 237221);
%directory = @list;
• A hash can be converted to an array:
@list = %directory;

Accessing a Hash Element

• Given the hash key, the value can be


accessed using ‘{ }’.
• Example:

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;
print “Atul’s number is $directory{“Atul”} \n”;

4
Modifying a Value

• By simple assignment:

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;

$directory{Sruti} = “453322”;
$directory{‘Chandan’} ++;

Deleting an Entry

• A (hash key, value) pair can be deleted


from a hash array using the “delete”
function.
¾Hash key has to be specified.

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;
delete $directory{Atul};

5
Swapping Keys and Values

• Why needed?
¾Suppose we want to search for a person,
given the phone number.

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;

%revdir = reverse %directory;


print “$revdir{237221} \n”;

Using Functions ‘keys’, ‘values’

• ‘keys’ returns all the hash keys as a


list.
• ‘values’ returns all the values as a list.

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;

@all_names = keys %directory;


@all_phones = values %directory;

6
An Example

• List all person names and telephone


numbers.

@list = qw (Rabi 258345 Chandan 325129 Atul


445287 Sruti 237221);
%directory = @list;

foreach $name (keys %directory) {


print “$name \t $directory{$name} \n”;
}

Subroutines

7
Introduction

• A subroutine …..
¾Is a user-defined function.
¾Allows code reuse.
¾Define ones, use multiple times.

How to use?

• Defining a subroutine
sub test_sub {
# the body of the subroutine goes here
# ……..
}
• Calling a subroutine
¾Use the ‘&’ prefix to call a subroutine.
&test_sub;
&gcd ($val1, $val2); # Two parameters
¾However, the ‘&’ is optional.

8
Subroutine Return Values

• Use the ‘return’ statement.


¾This is also optional.
¾If the keyword ‘return’ is omitted, Perl
functions return the last value evaluated.
• A subroutine can also return a non-
scalar.
• Some examples are given next.

Example 1

$name = ‘Indranil';
welcome(); # call the first sub
welcome_namei(); # call the second sub
exit;
sub welcome {
print "hi there\n";
}
sub welcome_name {
print "hi $name\n";
# uses global $name variable
}

9
Example 2

# Return a non-scalar
sub return_alpha_and_beta {
return ($alpha, $beta);
}

$alpha = 15;
$beta = 25;

@c = return_alpha_and_beta;
# @c gets (5,6)

Passing Arguments

• All arguments are passed into a Perl


function through the special array $_.
¾Thus, we can send as many arguments as
we want.
• Individual arguments can also be
accessed as $_[0], $_[1], $_[2], etc.

10
Example 3

# Two different ways to write a subroutine to add two


# numbers
sub add_ver1 {
($first, $second) = @_;
return ($first + $second);
}

sub add_ver2 {
return $_[0] + $_[1];
# $_[0] and $_[1] are the first two
# elements of @_
}

Example 4

$total = find_total (5, 10, -12, 7, 40);

sub find_total {
# adds all numbers passed to the sub
$sum = 0;
for $num (@_) {
$sum += $num;
}
return $sum;
}

11
‘my’ variables

• We can define local variables using


the ‘my’ keyword.
¾Confines a variable to a region of code
(within a block { } ).
¾‘my’ variable’s storage is freed
whenever the variable goes out of
scope.
¾All variables in Perl is by default
‘global’.

Example 5

$sum = 7;
$total = add_any (20, 10, -15);
# $total gets 15
sub add_any {
# local variable, won't interfere
# with global $sum
my $sum = 0;
for my $num (@_ ) {
$sum += $num;
}
return $sum;
}

12
Writing CGI Scripts in Perl

Introduction

• Perl provides with a number of


facilities to facilitate writing of CGI
scripts.
¾Standard library modules.
ƒ Included as part of the Perl distribution.
ƒ No need to install them separately.

#!/usr/bin/perl
use CGI qw (:standard);

13
• Some of the functions included in the
CGI.pm (.pm is optional) are:
¾header
ƒ This prints out the “Content-type” header.
ƒ With no arguments, the type is assumed to be
“text/html”.
¾start_html
ƒ This prints out the <html>, <head>, <title> and
<body> tags.
ƒ Accepts optional arguments.

¾end_html
ƒ This prints out the closing HTML tags,
</body>, >/html>.

• Typical usages and arguments would


be illustrated through examples.

14
Example 1 (without using CGI.pm)

#!/usr/bin/perl
print <<TO_END;
Content-type: text/html

<HTML> <HEAD> <TITLE> Server Details </TITLE>


</HEAD>
<BODY>
Server name: $ENV{SERVER_NAME} <BR>
Server port number: $ENV{SERVER_PORT} <BR>
Server protocol: $ENV{SERVER_PROTOCOL}
</BODY> </HTML>
TO_END

Example 2 (using CGI.pm)

#!/usr/bin/perl -wT
use CGI qw(:standard);

print header (“text/html”);


print start_html ("Hello World");
print "<h2>Hello, world!</h2>\n";
print end_html;

15
Example 3: Decoding Form Input

sub parse_form_data {
my %form_data;
my $name_value;
my @nv_pairs = split /&/, $ENV{QUERY_STRING};

if ( $ENV{REQUEST_METHOD} eq ‘POST’ ) {
my $query = “”;
read (STDIN, $query, $ENV{CONTENT_LENGTH});
push @nv_pairs, split /&/, $query;
}

foreach $name_value (@nv_pairs) {


my ($name, $value) = split /=/, $name_value;

$name =~ tr/+/ /;
$name =~ s/%([\da-f][\da-f])/chr (hex($1))/egi;
$value =~ tr/+/ /;
$value =~ s/%([\da-f][\da-f])/chr (hex($1))/egi;

$form_data{$name} = $value;
}
return %form_data;
}

16
Using CGI.pm

• The decoded form value can be


directly accessed as:
$value = param (‘fieldname’);
• An equivalent Perl code as in the last
example using CGI.pm
¾Shown in next slide.

Example 4

#!/usr/bin/perl -wT
use CGI qw(:standard);

my %form_data;
foreach my $name (param() ) {
$form_data {$name} = param($name);
}

17
Example 5: sending mail

#!/usr/bin/perl -wT
use CGI qw(:standard);

print header;
print start_html (“Response to Guestbook”);
$ENV{PATH} = “/usr/sbin”; # to locate sendmail
open (MAIL, “| /usr/sbin/sendmail –oi –t”);
# open the pipe to sendmail
my $recipient = ‘xyz@hotmail.com’;
print MAIL “To: $recipient\n”;
print MAIL “From: isg\@cse.iitkgp.ac.in\n”;
print MAIL “Subject: Submitted data\n\n”;

foreach my $xyz (param()) {


print MAIL “$xyz = “, param($xyz), “\n”;
}

close (MAIL);

print <<EOM;
<h2>Thanks for the comments</h2>
<p>Hope you visit again.</p>
EOM

print end_html;

18
SOLUTIONS TO QUIZ
QUESTIONS ON
LECTURE 23

19
Quiz Solutions on Lecture 23
1. Show an example illustrating the ‘split’
function.
$_=‘Red:Blue:Green:White:255';
@details = split /:/, $_;

2. Write a Perl code segment to ‘join’ three


strings $a, $b, and $c, separated by the
delimiter string “<=>”.
$new = join ‘<=>’, $sep, $a, $b, $c

Quiz Solutions on Lecture 23

3. What is the difference between =~ and !~?


=~ means “pattern is present”
!~ means “pattern is not present”

4. Is it possible to change the forward slash


delimiter while specifying a regular
expression? If so, how?
Using ‘m’ to specify the delimiter
if ($string =~ m@day@)

20
Quiz Solutions on Lecture 23

5. Write Perl code segment to search for


the presence of a vowel (and a
consonant) in a given string.
if ($string =~ /[aeiou]/) {
print "Found a vowel \n";
}
if ($string =~ /[^aeiou]/) {
print "Found a consonant\n";
}

Quiz Solutions on Lecture 23


6. How do you specify a RegEx indicating a
word preceding and following a space, and
starting with ‘b’, ending with ‘d’, with the
letter ‘a’ somewhere in between.
/\sb*a*d \s/
7. Write a Perl command to replace all
occurrences of the string “bad” to “good”
in a given string.
s/bad/good/g

21
Quiz Solutions on Lecture 23

8. Write a Perl code segment to replace all


occurrences of the string “bad” to “good”
in a given file.
open INP, “input.txt” or die “Error in open: $!”;
open OUT , “>$out.txt” or die “Error in write: $!”;

while <INP> {
s/bad/good/g;
print OUT “$_”;
}

close INP;
close OUT;

Quiz Solutions on Lecture 23

9. Write a Perl command to exchange the


first two words starting with a vowel in a
given character string.
s/([aeiou]*)\s([aeiou]*)\s/$2 $1/

10. What are the meanings of the variables


S`, $@, and S’?
$` means pre-match
$@ means present match
$’ means post match

22
QUIZ QUESTIONS ON
LECTURE 24

Quiz Questions on Lecture 23

1. How do we specify an associative array


using the ‘=>’ operator?
2. How can you convert a normal array to
an associative array?
3. How can you delete a (hash key, value)
pair from an associative array?
4. How are arguments passed to
subroutines?
5. What is the significance of ‘my’
variables?

23
Quiz Questions on Lecture 23

6. With the help of an example, illustrate


how the CGI.pm library can be used
to create CGI script programs.

24

You might also like