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

an element value can be found out by specifying the hash key value. 2 . Hash keys must be unique. also known as hashes. Associative Arrays Introduction • Associative arrays. A hash array name must begin with a ‘%’. a hash key and a value. Associative search. Accessing an element Unlike an array. Similar to a list Every list element consists of a pair.

Sruti => “237221” ). “Chandan”. “237221” ). “Atul”. Chandan => “325129”. %directory = ( Rabi => “258345”. %directory = ( “Rabi”. in proper sequence. “325129”. Whatever appears on the left hand side of ‘=>’ is treated as a double-quoted string. Atul => “445287”. “258345”. 3 . “445287”. “Sruti”. Specifying Hash Array • Two ways to specify: Specifying hash keys and values. Using the => operator.

• Example: @list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). print “Atul’s number is $directory{“Atul”} \n”. Conversion Array <=> Hash • An array can be converted to hash. %directory = @list. @list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). 4 . • A hash can be converted to an array: @list = %directory. %directory = @list. Accessing a Hash Element • Given the hash key. the value can be accessed using ‘{ }’.

value) pair can be deleted from a hash array using the “delete” function. $directory{‘Chandan’} ++. %directory = @list. delete $directory{Atul}. Deleting an Entry • A (hash key. 5 . %directory = @list. @list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). Modifying a Value • By simple assignment: @list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). $directory{Sruti} = “453322”. Hash key has to be specified.

@list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). Swapping Keys and Values • Why needed? Suppose we want to search for a person. %revdir = reverse %directory. given the phone number. %directory = @list. print “$revdir{237221} \n”. ‘values’ • ‘keys’ returns all the hash keys as a list. • ‘values’ returns all the values as a list. Using Functions ‘keys’. 6 . @all_names = keys %directory. @list = qw (Rabi 258345 Chandan 325129 Atul 445287 Sruti 237221). %directory = @list. @all_phones = values %directory.

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 .

&test_sub.. the ‘&’ is optional. How to use? • Defining a subroutine sub test_sub { # the body of the subroutine goes here # ……. Is a user-defined function.. use multiple times. &gcd ($val1. Allows code reuse. 8 . Define ones. $val2). Introduction • A subroutine …. } • Calling a subroutine Use the ‘&’ prefix to call a subroutine. # Two parameters However.

If the keyword ‘return’ is omitted. This is also optional. welcome(). • A subroutine can also return a non- scalar. # call the second sub exit. Example 1 $name = ‘Indranil'. • Some examples are given next. # uses global $name variable } 9 . } sub welcome_name { print "hi $name\n". # call the first sub welcome_namei(). Subroutine Return Values • Use the ‘return’ statement. sub welcome { print "hi there\n". Perl functions return the last value evaluated.

} $alpha = 15. # @c gets (5. $_[2]. Example 2 # Return a non-scalar sub return_alpha_and_beta { return ($alpha. $_[1]. $beta = 25. Thus. 10 . etc. $beta). • Individual arguments can also be accessed as $_[0].6) Passing Arguments • All arguments are passed into a Perl function through the special array $_. @c = return_alpha_and_beta. we can send as many arguments as we want.

} return $sum. return ($first + $second). Example 3 # Two different ways to write a subroutine to add two # numbers sub add_ver1 { ($first. for $num (@_) { $sum += $num. # $_[0] and $_[1] are the first two # elements of @_ } Example 4 $total = find_total (5. } sub add_ver2 { return $_[0] + $_[1]. -12. } 11 . 10. 7. sub find_total { # adds all numbers passed to the sub $sum = 0. 40). $second) = @_.

for my $num (@_ ) { $sum += $num. All variables in Perl is by default ‘global’. 10. $total = add_any (20. # $total gets 15 sub add_any { # local variable. } 12 . Example 5 $sum = 7. } return $sum. won't interfere # with global $sum my $sum = 0. Confines a variable to a region of code (within a block { } ). ‘my’ variable’s storage is freed whenever the variable goes out of scope. -15). ‘my’ variables • We can define local variables using the ‘my’ keyword.

No need to install them separately. Standard library modules. #!/usr/bin/perl use CGI qw (:standard). 13 . Writing CGI Scripts in Perl Introduction • Perl provides with a number of facilities to facilitate writing of CGI scripts. Included as part of the Perl distribution.

<title> and <body> tags. • Typical usages and arguments would be illustrated through examples. With no arguments. 14 .• Some of the functions included in the CGI. end_html This prints out the closing HTML tags.pm is optional) are: header This prints out the “Content-type” header. <head>. start_html This prints out the <html>. the type is assumed to be “text/html”. >/html>.pm (. </body>. Accepts optional arguments.

print start_html ("Hello World"). Example 1 (without using CGI. print end_html. 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. world!</h2>\n". print "<h2>Hello. 15 . print header (“text/html”).pm) #!/usr/bin/perl -wT use CGI qw(:standard).pm) #!/usr/bin/perl print <<TO_END.

$value) = split /=/. $value =~ s/%([\da-f][\da-f])/chr (hex($1))/egi. $ENV{CONTENT_LENGTH}). read (STDIN. if ( $ENV{REQUEST_METHOD} eq ‘POST’ ) { my $query = “”. $query. $ENV{QUERY_STRING}. push @nv_pairs. $query. $value =~ tr/+/ /. } foreach $name_value (@nv_pairs) { my ($name. Example 3: Decoding Form Input sub parse_form_data { my %form_data. my $name_value. $form_data{$name} = $value. split /&/. $name =~ tr/+/ /. $name_value. } 16 . } return %form_data. $name =~ s/%([\da-f][\da-f])/chr (hex($1))/egi. my @nv_pairs = split /&/.

my %form_data. • An equivalent Perl code as in the last example using CGI.pm • The decoded form value can be directly accessed as: $value = param (‘fieldname’). } 17 . Example 4 #!/usr/bin/perl -wT use CGI qw(:standard).pm Shown in next slide. foreach my $name (param() ) { $form_data {$name} = param($name). Using CGI.

print start_html (“Response to Guestbook”). $ENV{PATH} = “/usr/sbin”. foreach my $xyz (param()) { print MAIL “$xyz = “.in\n”. “\n”. } close (MAIL). print MAIL “From: isg\@cse.com’. print header.</p> EOM print end_html. param($xyz). <h2>Thanks for the comments</h2> <p>Hope you visit again. print MAIL “To: $recipient\n”. print <<EOM.ac. Example 5: sending mail #!/usr/bin/perl -wT use CGI qw(:standard). “| /usr/sbin/sendmail –oi –t”). print MAIL “Subject: Submitted data\n\n”. # to locate sendmail open (MAIL.iitkgp. 18 . # open the pipe to sendmail my $recipient = ‘xyz@hotmail.