Вы находитесь на странице: 1из 18

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 Atuls 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 variables 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