Sunteți pe pagina 1din 34

Lab Guide for Perl Scripting

Author(s)
Authorized by
Creation/Revision Date
Version

Nihar Bhatt, Pragati Sheel ,Sowmya


Kamath K, Jayaram Reddy Chamkura
Srikantan Moorthy
May 2009
2.00

Company Confidential

COPYRIGHT NOTICE
All ideas and information contained in this document are the intellectual property of
Education and Research Department, Infosys Technologies Limited. This document is
not for general distribution and is meant for use only for the person they are
specifically issued to. This document shall not be loaned to anyone, within or outside
Infosys, including its customers. Copying or unauthorized distribution of this
document, in any form or means including electronic, mechanical, photocopying or
otherwise is illegal.
Education and Research Department
Infosys Technologies Limited
Electronic City
Hosur Road
Bangalore - 561 229, India.
Tel: 91 80 852 0261-270
Fax: 91 80 852 0362
www.infy.com
mailto:E&R@infy.com

Infosys Technologies Limited

Document Revision History

Document Revision History


Version
0.00a

Date
Mar 2007

1.0

June 2007

2.0

May 2009

ER/CORP/CRS/LA82/005

Author(s)
Nihar Bhatt
Pragati Sheel
Nihar Bhatt
Pragati Sheel
Sowmya Kamath K
Jayaram Reddy
Chamakura

Reviewer(s)
Ajeesh G. P.

Comments
Initial Draft

Ajeesh G.P.

Review comments
incorporated.
FP Restructuring 2009

Amit Tewari

Version No.: 1.0


i

Infosys Technologies Limited

Table of Contents

Contents

COPYRIGHT NOTICE ................................................................................................... II


DOCUMENT REVISION HISTORY ...................................................................................... I
CONTENTS .............................................................................................................. II
CONTEXT ............................................................................................................... 1
DAY 1 ASSIGNMENTS .................................................................................................. 1
ASSIGNMENT 1: CREATE THE FIRST PERL SCRIPT ......................................................................... 1
ASSIGNMENT 2: UNDERSTANDING THE USE OF SCALAR VARIABLES ......................................................... 2
ASSIGNMENT 3: UNDERSTANDING THE USE OF WARN AND PRINTF STATEMENTS ............................................ 4
ASSIGNMENT 4: USING IF STATEMENT AND DO..UNTIL LOOP .............................................................. 4
ASSIGNMENT 5: INTRODUCING ARRAYS .................................................................................. 5
ASSIGNMENT 6: STORING IN ARRAYS .................................................................................... 6
ASSIGNMENT 7: ADDING AND DELETING ELEMENTS OF AN ARRAY ......................................................... 6
ASSIGNMENT 8: ARRAY CONVERSIONS ................................................................................... 7
ASSIGNMENT 9: INTRODUCTION OF HASH VARIABLE ...................................................................... 7
ASSIGNMENT 10: USING FOREACH STATEMENT......................................................................... 8
ASSIGNMENT 11: MORE ON HASH VARIABLES ............................................................................ 8
ASSIGNMENT #: EXERCISES FOR SELF REVIEW ............................................................................ 9
DAY 2 ASSIGNMENTS ................................................................................................ 11
ASSIGNMENT 1: INTRODUCTION TO SUBROUTINES ....................................................................... 11
ASSIGNMENT 2: PASSING ARGUMENTS TO SUBROUTINES ................................................................. 11
ASSIGNMENT 3: USING MY VARIABLE ................................................................................... 12
ASSIGNMENT 4: USING SUBROUTINES, JOIN AND SPLIT .................................................................. 12
ASSIGNMENT 5: USING LOCAL VARIABLE ................................................................................ 13
ASSIGNMENT 6: USING COMMAND LINE ARGUMENTS .................................................................... 13
ASSIGNMENT 7: MORE ON COMMAND LINE ARGUMENTS ................................................................. 14
ASSIGNMENT 8: UNDERSTANDING PATTERN MATCHING FOR NUMBERS .................................................... 14
ASSIGNMENT 9: INTRODUCTION OF TRANSLATION IN PERL ............................................................... 15
ASSIGNMENT 10: UNDERSTANDING USE OF TRANSLATION IN PERL ........................................................ 16
ASSIGNMENT 11: INTRODUCTION TO FILE HANDLING .................................................................... 16
ASSIGNMENT 12: UNDERSTANDING REPORTING IN A FILE ................................................................ 17
ASSIGNMENT 13: UNDERSTAND FILE HANDLING AND PATTERN MATCHING ............................................... 18
ASSIGNMENT 14: UNDERSTANDING FILE HANDLING SEEK FUNCTION .................................................... 19
ASSIGNMENT #: EXERCISES FOR SELF REVIEW ........................................................................... 20
DAY 3 ASSIGNMENTS ................................................................................................ 21
ASSIGNMENT 1: UNDERSTANDING DATABASE CONNECTIVITY WITH ORACLE ............................................... 21
ASSIGNMENT 2: UNDERSTANDING PARAMETERIZED QUERY ............................................................... 23
ASSIGNMENT 3: UNDERSTANDING DATABASE OPERATIONS................................................................ 24

ER/CORP/CRS/LA82/005

Version No. 1.0

ii

Infosys Technologies Limited

Table of Contents

ASSIGNMENT 4: UNDERSTANDING CALLING AN ORACLE STORED PROCEDURE .............................................. 25


ASSIGNMENT 5: UNDERSTANDING WEB DEVELOPMENT USING CGI ....................................................... 26
ASSIGNMENT 6: UNDERSTANDING GET AND POST METHODS............................................................ 28
ASSIGNMENT 7: UNDERSTANDING USE OF COOKIES IN PERL .............................................................. 29
ASSIGNMENT 8: UNDERSTANDING IMPLEMENTATION CGI AND DATABASE ................................................. 29
DAY 1 : ANSWERS FOR SELF REVIEW EXERCISES ........................................ ERROR! BOOKMARK NOT DEFINED.
DAY 2 : ANSWERS FOR SELF REVIEW EXERCISES ........................................ ERROR! BOOKMARK NOT DEFINED.

ER/CORP/CRS/LA82/005

Version No. 1.0

iii

Infosys Technologies Limited

Lab Guide for Perl Scripting

Context
This document contains assignments to be completed as part of the hands on for the
subject Perl Scripting (Course code: LA82).
Note: In order to complete the course, assignments in this document must be
completed in the sequence mentioned.

Day 1 Assignments
Assignment 1: Create the first Perl Script
Objective: To learn how to write a Perl Script, to interpret and execute it.
Problem Description: Writing a Perl Script to display Hello Perl!
Estimated time: 10 minutes
Step 1: Create a file named First.pl using any editor. Eg.Notepad.
Step 2: Open the file and type the following code
#!c:/perl/bin/perl #Using Perl Interpreter
#########################################################
# FileName
: hello.pl
# Description : First Perl Script. Prints "Hello Perl!"
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 26-Feb-2007
#########################################################
#Clearing the screen
system("cls");
#Print the Hello Perl Message
print "Hello Perl!";
########################################################
# End of file hello.pl
########################################################

ER/CORP/CRS/LA82/5

Version No. 1.0

1 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Step 3: Save and quit from the editor.


Step 4: Select the Start, from Programs select the Active Perl Command Prompt.
Step 5: To execute the program, select the appropriate directory and type the
following command.
perl hello.pl
Your program executes now and you see the following output:
Hello Perl!

Summary of this assignment:

How to type a Perl script in the editor


How to execute your script through Perl interpreter

Assignment 2: Understanding the use of scalar variables


Objective: To find the area of a circle and to understand the use of scalar variables.
Problem Description: Writing a Perl script to find the area of a circle.
Estimated time: 15 minutes
Step 1: Create a new Perl script file Area_Circle.plunder the directory
Day1_Assignments
Step 2: Type the following code:
#!c:/perl/bin/perl #Using Perl Interpreter
#########################################################
# FileName
: Area_Circle.pl
# Description : Finding the area of a circle.
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 26-Feb-2007
#########################################################

ER/CORP/CRS/LA82/5

Version No. 1.0

2 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

#Clearing the screen


system("cls");
#Giving the values for Pi and Radius of the circle
$Pi=3.14;
$Radius=3;
#Calculating the area of a circle by pi * r^2 formula
$Area= $Pi * $Radius * $Radius;
#Printing the calculated area
Print "Area = $Area\n";
########################################################
# End of file Area_Circle.pl
########################################################

Step 3: Execute the script by typing:$ perl Area_Circle.pl


You will get a compilation error as shown in below screen.

Step 4: Error message says, (Do you need to predeclare Print?). The number 23
indicate the line number in which the error occurred.
Go to the line indicated by compiler and inspect the error.
Step 5: Change the case of Print to print and execute again.
Step 6: If there are no typographical errors, program should execute successfully.
The program executes and you see the desired output on the screen.

Summary of this assignment:

ER/CORP/CRS/LA82/5

Version No. 1.0

3 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Automatic type conversion that happens when an expression is evaluated


Use of scalar variables
Caution to be exercised when typing even a simple statement

Assignment 3: Understanding the use of warn and printf statements


Objective: To understand the use of warn and printf statements.
Problem Description: Writing the Perl script to display the details entered according
to the given scenario.

Estimated time: 10 minutes


Step 1: Declare scalar variables of AccountNo, AccountType, Balance
Step 2: Input the data like 10001, SB for AccountNo and AccountType respectively.
Step 3: Get the data from user for Balance by using statement
Balance=<STDIN>;
Step 4: Check for the balance by
Step 5: if (Balance > 0)
Use printf statements and display the details.
Step 6: Write the warn statement in the else part saying Balance is insufficient.

Summary of this assignment:

Use of warn statement


Use of printf statement

Note:
Example: Usage of printf statement:
$Number=1;
printf(Size of int data type: %d,$Number);
Example: syntax of warn statement:
warn Wrong Choice;

Assignment 4: Using if Statement and do..until loop

ER/CORP/CRS/LA82/5

Version No. 1.0

4 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Objective: To understand the use of control structure IF and the do until loop
Problem Description: Writing a Perl script to calculate the grade for a student based
on their marks.
Estimated time: 15 minutes
Step 1: Create a Perl script file Use_Of_If.pl
Step 2: Accept the name and the marks of the student in scalar variables. Store the
resultant grade also.
Step 3: Display the name, marks and grade in a formatted output.
Step 4: Check is the user wants to repeat the process. Use the dountil loop to
repeat the above steps

Summary of this assignment:

Use of IF statement
Use of do..until loop
User input from the terminal
Note: Calculate the grade according to ENR Evaluation Policy.

Assignment 5: Introducing Arrays


Objective: To understand the concept of storing data in an array from terminal and
accessing it.
Problem Description: Writing a Perl script to store data from terminal to an array.
Estimated time: 10 minutes
Step 1: Create a Perl script file TerminalInputI.pl
Step 2: Use an array variable that takes multiple lines of input from the Terminal
(using <STDIN>). Use CTRL+Z to mark the end of input.
Step 3: Display the array elements and length of the array to the user.
Summary of this assignment:

Taking input from the Terminal

ER/CORP/CRS/LA82/5

Version No. 1.0

5 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Storing structure of array


Accessing array elements

Assignment 6: Storing In Arrays


Objective: To understand the concept of storing data in an array and to access it
through indices.
Problem Description: Writing a Perl script to display a particular line.
Estimated time: 10 minutes
Step 1: Create a Perl script file TerminalInputII.pl
Step 2: Modify the Assignment No. 5, remove the display statement and add the
following statements.
Step 3: Read the line number from the user.
Step 4: Display the line corresponding to the line number.

Summary of this assignment:


Accessing array elements in depth
More logic coverage on Terminal input

Assignment 7: Adding and Deleting elements of an Array


Objective: To understand the concept of adding and deleting data in an array.
Problem Description: Writing a Perl script to add and delete an element in an array
in queue fashion.
Estimated time: 15 minutes
Step
Step
Step
Step

1:
2:
3:
4:

Create a Perl script file Add_Del_Array.pl


Initialize an array with few elements.
Display the array elements.
Display a menu as below.

1.
2.
3.
4.
5.

Add element to the beginning of the array


Delete element from the beginning of the array
Add element to the end of the array
Add element from end of the array
Exit

ER/CORP/CRS/LA82/5

Version No. 1.0

6 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Step 5: Use the array functions POP, PUSH, UNSHIFT and SHIFT to implement the
choice.
Summary of this assignment:
Addition and Deletion of elements in an ARRAY.
More logic coverage on arrays.
Note: Use POP,PUSH, UNSHIFT and SHIFT.

Assignment 8: Array Conversions


Objective: To understand the concept of changing string to array and back to string
and of sorting an array.
Problem Description: Writing a Perl script to sort a string.
Estimated time: 10 minutes
Step 1: Create the Perl script file sortstring.pl
Step 2: Read a sentence from the user.
Step 3: Convert the string to an array (using substr) i.e. each word is put as one array
element.
Step 4: Sort the array and convert it back to a string (using the . operator).
Step 5: Display the final string.
Summary of this assignment:

Converting a string to an array and vice-versa


Sorting an array

Assignment 9: Introduction of Hash Variable


Objective: To understand the concept Hash variable.
Problem Description: Write a Perl script file which ask for the Product Category and
prints the Category and the Stock available based on the following mapping table.

ER/CORP/CRS/LA82/5

Version No. 1.0

7 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Estimated time: 20 minutes


Step 1: Create a Hash variable having the following elements
Product Table
Category
Stock Available
Clothes
150
Shoes
100
Cosmetics
125
Step 2: Read the Category of the product. Display the Stock available for valid input,
Error message otherwise.
Summary of this assignment:

Use of Hash Variable

Assignment 10: Using FOREACH Statement


Objective: To understand the use of FOREACH control structure, use of arrays and
hashes.
Problem Description: Writing a Perl script to find the cubes of numbers entered by
the user.
Estimated time: 15 minutes
Step
Step
Step
Step

1:
2:
3:
4:

Create a Perl script file Use_Of_ForEach.pl


Accept numbers from the terminal. Use array to store them.
Calculate the cubes of the numbers and store them into a hash
Display the numbers and the cubes in a formatted output.

Summary of this assignment:

Use of FOREACH statement


User input from the terminal to an array
Use of Hash

Assignment 11: More on Hash Variables


Objective: To understand the concept Hash variable.

ER/CORP/CRS/LA82/5

Version No. 1.0

8 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Problem Description: Writing a Perl script to Count the occurrence of each word in a
string.
Estimated time: 20 minutes
Step
Step
Step
Step

1:
2:
3:
4:

Create a Perl script file wordscount.pl.


Read a string from the user.
Calculate the count of occurrence of each word.
Display the count along with the words.

Summary of this assignment:

Hash variables in depth

Note: (Hint: - change the string to an array)

Assignment #: Exercises for Self Review


1) What is a header comment, and where does it appear in a program?
2) What is wrong with the following program?
#!c:/perl/bin/perl
$inputline = <STDIN>;
print ($inputLine);
3) What is wrong with the following program?
#!c:/perl/bin/perl
$inputline = <STDIN>;
# print my line! print($inputline);
4) What is the result when the following expression is evaluated?
14 + 6 * 3 - 10 / 2
5) Which of the following are legal scalar variable names?
a.
b.

$hello
$_test

ER/CORP/CRS/LA82/5

Version No. 1.0

9 of 29

Infosys Technologies Limited

c.
d.
e.
f.

Lab Guide for Perl Scripting

$now_is_the_time_to_come_to_the_aid_of_the_party
$fries&gravy
$96tears
$tea_for_2

6) What is wrong with the following program? (Hint: there might be more than one
bug!)
#!c:/perl/bin/perl
$value = <STDIN>;
if ($value = 17) {
print ("You typed the number 17.\n");
else {
print ("You did not type the number 17.\n");
7) Find and fix the bugs in the following program:
#!c:/perl/bin/perl
$num = <STDIN>;
chop ($num);
$x = "";
$x += "hello";
if ($x != "goodbye" | $x == "farewell") {
$result = $num eq 0 ? 43;
} else {
$result = ++$num++;
}
print("the result is $result\n");
8) What happens when you refer to an array element that has not yet been defined?
9) What is wrong with the following program? (See if you can figure out what's wrong
without checking the listings in today's lesson.)
#!c:/perl/bin/perl
@input = <STDIN>;
$currline = 1;
while ($currline < @input) {
@words = split(/ /, $input[$currline]);
@words = sort(@words);
$input[$currline] = join(" ", @words);
$currline++;
}
print (@input);
10) How can I know how many entries are in a hash?

ER/CORP/CRS/LA82/5

Version No. 1.0

10 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Day 2 Assignments
Assignment 1: Introduction to Subroutines
Objective: To understand calling a subroutine.
Problem Description: Writing a Perl script that calls a subroutine to calculate the
sum of an integer array passed as an argument.
Estimated time: 15 minutes
Step 1: Create a Perl script file sum.pl.
Step 2: Read the numbers from the user.
Step 3: Write a subroutine which calculates and returns the sum of these two
numbers.
Step 4: Call the subroutine with user input and display the return value.

Summary of this assignment:

Learning to pass arguments to a subroutine

Assignment 2: Passing arguments to Subroutines


Objective: To understand argument passing to Subroutines.
Problem Description: Writing a Perl script that calls a subroutine to validate the
elements of an array passed to it.
Estimated time: 15 minutes
Step 1: Create a Perl script file numbercharacter.pl.
Step 2: Read the array elements (single characters) from the user and pass it to the
subroutine by using call by reference.
Step 3: Count the number of Integers and characters in the array.
Step 4: Display the count in the subroutine.
Summary of this assignment:

ER/CORP/CRS/LA82/5

Version No. 1.0

11 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Argument passing to a subroutine

Assignment 3: Using MY variable


Objective: To understand concept of my variable.
Problem Description: Writing a Perl script that calls a subroutine to calculate the
sum of numbers present in an array passed to it.
Estimated time: 15 minutes
Step 1: Create a Perl script file myvariable.pl.
Step 2: Read the numbers to be added.
Step 4: Call the subroutine to find the addition of the numbers. Print the result in the
subroutine.
Step 5: Print the sum of numbers, using the variable declared in the subroutine, in
the calling block. Notice the value printed.
Step 5: Declare the variable used to store the sum of numbers as my variable. Now
observe the answer.

Summary of this assignment:

Use of My variable

Note: Use the same variable name to store the results for the addition
of numbers and concatenation of strings.

Assignment 4: Using Subroutines, Join and Split


Objective: To find the occurrence of a character in a string passed as argument.
Problem Description: Writing a Perl script that calls a subroutine to count the
occurrence in a string passed to it.

ER/CORP/CRS/LA82/5

Version No. 1.0

12 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Estimated time: 15 minutes


Step 1: Create a Perl script file characteroccurence.pl.
Step 2: Accept the string and the letter from the terminal. Pass the string and the
letter to the subroutine and get the result back.
Step 3: Display the result in the proper format.

Summary of this assignment:

Use of arrays, split(), join()


Use of subroutines

Assignment 5: Using Local Variable


Objective: To understand the concept of local variable.
Problem Description: Writing a Perl script to sort and display the result using local
variable and subroutines.
Estimated time: 15 minutes
Step 1: Write a program that calls a subroutine to sort the numbers passed to it and
calls a display subroutine to display them.
Step 2: Create a Perl script file local.pl.
Step 3: Accept the string from the terminal. Pass the string to the subroutine and sort
the array and display the result in Display subroutine without passing any arguments.
Summary of this assignment:

Subroutine in depth
Use of local variable

Assignment 6: Using Command Line Arguments


Objective: To understand the concept of command line arguments.
Problem Description: Writing a Perl script to perform the arithmetic operation on the
given operands as command line arguments.
Estimated time: 10 minutes

ER/CORP/CRS/LA82/5

Version No. 1.0

13 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Step 1: Create a Perl script file Arguments.pl.


Step 2: Accept the operands and the operator from the command line (eg. 12 + 13).
Implement it for the four basic operators (+, -, *, /).
Step 3: Calculate and display the result.
Summary of this assignment:

Use of Command line arguments

Assignment 7: More on Command Line Arguments


Objective: To understand the concept of command line arguments in depth.
Problem Description: Writing a Perl script that takes a list of files and indicates for
each file, whether the user has read, write or execute permissions.
Estimated time: 10 minutes
Step 1: Create a Perl script file FilePermissions.pl.
Step 2: Accept the file name from the command line.
Step 3: Check for the existence of file and if exist check for the read, write and
execute permissions.
Step 4: Display the file name and the permissions available to the user for the file.
Summary of this assignment:

Use of Command line arguments

Note: Use the file test operators concept.


-e <filename>: to check whether the file exist or not.
-r <filename>: to check whether the file has read permission.
-w <filename>: to check whether the file has write permission.
-x <filename>: to check whether the file has execute permission.

Assignment 8: Understanding pattern matching for numbers


Objective: To understand pattern matching for checking numeric/character data
only.

ER/CORP/CRS/LA82/5

Version No. 1.0

14 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Problem Description: Writing a Perl script to validate a string containing only


numbers or only characters.
Estimated time: 15 minutes
Step 1: Create a Perl script file MatchingNumbers.pl.
Step 2: Accept Age of the user into a scalar. Pass the age to the subroutine to check
if the scalar contains only numbers.
Step 3: Accept Age of the user into a scalar. Pass the name to another subroutine to
check if the scalar contains characters.
Step 4: Display the appropriate result in the subroutine itself.

Summary of this assignment:

Learning pattern matching

Assignment 9: Introduction of Translation in Perl


Objective: To understand the use of translation (tr) in Perl.
Problem Description: Write a program that calls a subroutine that deletes all the
numbers and multiple occurrences of spaces in the array passed to it.
Estimated time: 10 minutes
Step 1: Create a Perl script file TransDelSqueeze.pl.
Step 2: Accept the string from the terminal. Pass the string to the subroutine which
deletes all the numbers present in it and removes the multiple occurrences of spaces
with one space.
Step 3: Display the array retrieved from the subroutine.

Summary of this assignment:

Learning translation in Depth


Note: Use the (d, c & s) options of tr operator for the translation
related assignments.
It can be also done by lc, uc, lcfirst and ucfirst operators. Try to
explore them on yourself.

ER/CORP/CRS/LA82/5

Version No. 1.0

15 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Assignment 10: Understanding use of translation in Perl


Objective: To understand the use of translation (tr) in Perl.
Problem Description: Writing a Perl script that validates the string and ask for the
user for the case conversion.
Estimated time: 15 minutes
Step 1: Create a Perl script file ChangeCase.pl.
Step 2: Accept the string from the terminal. Validate the String and if valid pass the
string to the subroutine which displays a menu with two options. First one for
conversion from lowercase to uppercase and the second one for conversion from
upper case to lower case.
Step 3: Display the array after the conversion.

Summary of this assignment:

Learning translation in Perl


How to change case in Perl

Assignment 11: Introduction to File Handling


Objective: To understand the concept of File Handling.
Problem Description: Writing a Perl script to understand the concept of file handling.
Estimated time: 10 minutes
Step 1: Create a Perl script file FileCreation.pl.
Step 2: Write the code given below and analyze the working of the code.

#!c:/perl/bin/perl #Using Perl Interpreter


#########################################################
# FileName
: FileCreation.pl
# Description : Perl Script to understand file handling
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 26-Feb-2007
#########################################################
# Opening the file in write mode

ER/CORP/CRS/LA82/5

Version No. 1.0

16 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

open(DATA,">file.txt") or die "an error occured: $!";


#Asking the user for input
print "Enter the Data to be written in the file : - \n";
chomp(@InputData=<>);
#Writing the data entered into the file using filehandle
print DATA @InputData;
#Closing the file
close(DATA);
#Clearing the screen
system("clear");
#Opening the file in read mode
open(DATA,"<file.txt") or die "an error occured: $!";

print "The contents of the file are : -" ;


#Looping through the file and printing the contents of the file
while(<DATA>)
{
print "$_\n";
}
#Closing the file
close(DATA);
########################################################
# End of file FileCreation.pl
########################################################

Summary of this assignment:

Creating, Opening and Closing of a file


Reading and Writing to a file

Assignment 12: Understanding reporting in a File

ER/CORP/CRS/LA82/5

Version No. 1.0

17 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Objective: To understand creating a report file.


Problem Description: Writing a Perl script to create a formatted report file.
Estimated time: 20 minutes
Step 1: Create a Perl script file ReportFile.pl.
Step 2: Write a program which takes the input from the terminal and store the data
in a file Employee.txt in the following format.
Employees
ID
Name
Phone
-------------------------1
Nihar
2000
2
Pragati
3000
3
Ajeesh
4000
Step 3: Clear the screen after writing to the file and read and display the contents of
the file.
Summary of this assignment:

Use of format function


Creation of a formatted output in a file

Note: Use the format function to write in the above format.

Assignment 13: Understand File Handling and Pattern Matching


Objective: To understand use of pattern matching in a File.
Problem Description: Writing a Perl script to replace string in a file.
Estimated time: 20 minutes
Step 1: Create a Perl script file FilePattern.pl.
Step 2: Create a file ChangeFile.txt with the following contents.

ER/CORP/CRS/LA82/5

Version No. 1.0

18 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Infy is my dream company.


Biggest campus of Infy is in Mysore.
I am in Infy.
Replace the text.
Step 3: Write a program that read contents of ChangeFile.txt and replace Infy with
Infosys.
Summary of this assignment:

Understanding pattern matching in files

Note: Use the concepts of arrays and pattern matching.

Assignment 14: Understanding File Handling Seek function


Objective: To understand the use of seek function in file handling.
Problem Description: Writing a Perl script to search a specific record in a file and
modify the telephone numbers.
Estimated time: 20 minutes
Step 1: Create a Perl script file TelDir.pl.
Step 2: Use the file Employee.txt created before.
Step 3: Read the employee number from the user.
Step 4: If the employee number is present then read the new four digit telephone
number.
Step 5: Update the record of the employee with the new telephone number.

Summary of this assignment:

Use of seek and eof function


File handling in depth

ER/CORP/CRS/LA82/5

Version No. 1.0

19 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Note: Use the eof () and seek () functions.

Assignment #: Exercises for Self Review


1) Consider the following program:
#!c:/perl/bin/perl
$total = 0;
@list = (1, 2, 3);
@list2 = &my_sub;
sub my_sub {
local ($total);
$total = 1;
@list = (4, 5, 6);
}
What are the values stored in the following variables at the end of this program?
a. $total
b. @list
c. @list2
2) What does the following subroutine return?
sub sub1 {
$count = $sum = 0;
while ($count <= 10) {
$sum += $count;
$count++;
}
}
3) Write a program that takes a list of files from the command line and examines
their size. If a file is bigger than 10,000 bytes, print
File name is a big file!
where name is a placeholder for the name of the big file.
4) How many levels of nested subroutines can a program have?
5) How many command-line arguments can I specify?

ER/CORP/CRS/LA82/5

Version No. 1.0

20 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

6)
a.
b.
c.
d.
e.

What do the following patterns match?


/a|bc*/
/[\d]{1,3}/
/\bc[aou]t\b/
/(xy+z)\.\1/
/^$/

7)
a.
b.
c.
d.
e.

Write patterns that match the following:


Five or more lowercase letters (a-z).
Either the number 1 or the string one.
string of digits optionally containing a decimal point.
Any letter, followed by any vowel, followed by the same letter again.
One or more + characters.

8) Julius Ceasar is said to have used the famous Ceasar Cypher to encrypt his
communications with Rome. When encrypting, the Ceasar Cypher substitutes
letter-for-letter like this:
A -> C
B -> D
C -> E
...
X -> Z
Y -> A
Z -> B
Write a program that performs a Ceasar Cypher on its input.
As a test, if you feed the program "Ceasar Cypher", you should get "Egcuct
Earjgt". Be especially careful that the "y" in "cypher" maps to an "a".

Day 3 Assignments
Assignment 1: Understanding database connectivity with Oracle
Objective: To perform database connectivity with Oracle.
Problem Description: Writing a Perl script to run a query to fetch data from oracle.
Estimated time: 10 minutes
Step 1: Create a file DatabaseConnect.pl.

ER/CORP/CRS/LA82/5

Version No. 1.0

21 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Step 2: Type and analyze the code given below to connect and run a simple query
given below.
#!c:/perl/bin/perl #Using Perl Interpreter
#########################################################
# FileName
: DatabaseConnect.pl
# Description : Perl script to perform database connectivity
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 18-May-2009
#########################################################
use DBI; #Using DBI module
use DBD::Oracle; #Using DBD-Oracle module
#Connecting to database.
my $dbh = DBI->connect('dbi:Oracle:<Connection
string>','<UserID>','<Password>');
#Statement to create oracle table
my $sql = qq{ CREATE Table Account
(accountno NUMBER(4) PRIMARY KEY,
customerID NUMBER(3) constraint FK_Account
references Customer(custID),
accounttype CHAR(2) check (accounttype in
('SB','CA')),
DOP DATE,Amount NUMBER(7,2),
Status CHAR(1) check (Status in ('F','C'))
)};
my $sth = $dbh->do($sql);
#Disconnecting from the database
$dbh->disconnect();

Step 3: Verify in oracle if table is created and insert 5 records into this table.
Summary of this assignment:

Understanding the concept of database connectivity


Connection, operation and closure to database

ER/CORP/CRS/LA82/5

Version No. 1.0

22 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Note: Replace <Connection string>, <UserID>, <Password> with your


database information.

Assignment 2: Understanding parameterized query


Objective: To perform database connectivity with Oracle.
Problem Description: Writing a Perl script to run a query to fetch data from oracle.
Estimated time: 10 minutes
Step 1: Create a file DatabaseConnect.pl.
Step 2: Type and analyze the code given below to connect and run a simple query
given below.

#!c:/perl/bin/perl #Using Perl Interpreter


#########################################################
# FileName
: DatabaseConnect.pl
# Description : Perl script to perform database connectivity
# And simple fetch operation from oracle.
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 22-Jun-2007
#########################################################
use DBI; #Using DBI module
use DBD::Oracle; #Using DBD-Oracle module
#Connecting to database.
my $dbh = DBI->connect('dbi:Oracle:<Connection
string>','<UserID>','<Password>');
print enter the account number:;
$Accno=<>;
chomp $Accno;
#Statement to fetch data from oracle table
my $sql = qq{ SELECT c.name, a.accounttype,
a.amount FROM account a, customer c
where a.customerid=c.custid and a.accountno=?};

ER/CORP/CRS/LA82/5

Version No. 1.0

23 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

my $sth = $dbh->prepare( $sql );


#Executing the statement created above
$sth->execute($Accno);
#declaring and binding the corresponding variables to the column names
my($customerName, $accounttype, $currentamount);
$sth->bind_columns(\$customerName,\$accounttype,\$currentamount);
#Looping through to print the data in the table
if( $sth->fetch() ) {
print "Customer Name :$customerName\n;
Print Account Type: $accounttype \n;
Print Current Balance: $currentamount\n";
}
#Finishing the statement execution
$sth->finish();
#Disconnecting from the database
$dbh->disconnect();

Summary of this assignment:

Understanding the parameterized query


Use of statement handlers

Note: Replace <Connection string>, <UserID>, <Password> with your


database information.

Assignment 3: Understanding database operations


Objective: To perform database operations.

ER/CORP/CRS/LA82/5

Version No. 1.0

24 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Problem Description: Writing a Perl script to perform insert, update and display of
data from Oracle.
Estimated time: 30 minutes
Step 1: Create a file DMLOperation.pl.
Step 2: Create the menu-driven script
1. Insert Customer
2. Insert Account
3. Update Account
4. Delete Account
5. View Customer Data
6. View Account Data
7. Exit
Step 3: Implement option 1 using DB handle.
Step 4: Implement option 2 using statement handle.
Step 5: For option 3, create an update string using the inputs and then use statement
handle to update the table.
Step 6: Implement option 4 as parameterized query.
Step 7: Implement 5 using fetch_array()
Step 8: Implement 6 using fetch().
Summary of this assignment:

Understanding the implementation of database operations

Assignment 4: Understanding calling an oracle stored procedure


Objective: To execute an oracle Stored Procedure from PERL.
Problem Description: Writing a Perl script to perform execute an oracle stored
procedure
Estimated time: 25 minutes
Step 1: Write a stored procedure in SP for implementing a transaction.
1. Parameters AccountNo, Amount, Transaction type(W,D) are IN
parameters and there is one OUT parameter.
2. Enter the record into transaction table if accountno and amount is
valid
3. Update the amount in account table.
4. return -1 for invalid account, -2 for invalid amount, -3 for closed
account or -4 for errors as OUT parameter
ER/CORP/CRS/LA82/5

Version No. 1.0

25 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

5. Return Updated amount if successful.


Step
Step
Step
Step

2:
3:
4:
5:

Create a file Transaction.pl.


Input the Account No, Amount and transaction type from the user.
Call the SP and Handle the OUT parameter.
Display Amount if Successful or a meaningful message otherwise.

Assignment 5: Understanding Web Development using CGI


Objective: To Design Dynamic Web pages using Perl CGI
Problem Description: to create Guest book to accept user comments
Estimated time: 15 minutes
Step 1: Create Web Form (guestbook.pl) to enter Name, E-mail and comments.
Step 2: Type and analyze the code given below to generate simple guest book form
shown below
#!c:/perl/bin/perl #Using Perl Interpreter
#########################################################
# FileName
: Guestbook.pl
# Description : CGI script to generate simple Guest Book form.
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 22-Jun-2007
#########################################################
print "Content-type:text/html\n\n"; #printing HTML header
print <<SET
#here document for HTML code
<title>Guest Book Form</title>
<body >
<center>
<H1 align=center>Guest Book Form</H1>
#creating Guest book form
<form action="guest.pl" method="get" >
<table>
<tr><td>Name</td><td><input name="name" type="text"
value=""></td></tr>
<tr><td>E-Mail</td><td><input name="email" type="text"
value=""></td></tr>
<tr><td>Comments</td><td>
<TEXTAREA name="comments" rows="10" cols="32"></TEXTAREA></td></tr>
</table><br><br>

ER/CORP/CRS/LA82/5

Version No. 1.0

26 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

<input type="submit" value="Add Entry">


</form>
</body>
</html>
SET #End of SET

Step 3: Create the guest.pl to generate dynamic web page to display the data
received from form in guestbook.pl
#!c:/perl/bin/perl #Using Perl Interpreter
#########################################################
# FileName
: Guest.pl
# Description : CGI script to display input received from
# Guestbook.pl.
# Author
: E&R Department, Infosys Technologies Ltd.
# Date
: 22-Jun-2007
#########################################################
# Split name-value pairs using & in QUERY_STRING
@inputs = split(/&/, $ENV{QUERY_STRING});
#replacing the Hex values in input with equivalent characters
foreach $input (@inputs) {

ER/CORP/CRS/LA82/5

Version No. 1.0

27 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

($name, $val) = split(/=/, $input);


$val=~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$val =~ tr/+/ /;
$FORM{$name} = $val;
}
use CGI qw/:standard/;

#using CGI module standard set

print header;
#printing HTML Header
print title("Dynamic Page Example");
print h1({align=>'center'},"Dynamic Page");
#Displaying output in tabular form
print "Dear $FORM{'name'},<BR>Thanks for filling out our Form.
Good Luck<br><br>";
print table({border=>2},Tr({align=>CENTER,valign=>TOP},
[
th('Name:').td($FORM{'name'}),
th('E-mail').td($FORM{'email'}),
th('Comments').td($FORM{'comments'})
]
)
);

Summary of this assignment:


Understanding the Dynamic Web Page generation in Perl.

Assignment 6: Understanding GET and POST Methods


Objective: To understand Get and POST methods in web pages
Problem Description: to create web page and send data by using POST and GET
methods
Estimated time: 10 minutes
Step 1: Create Web Form (EmployeeDetails.pl) to enter Name, Employee Number and
E-mail
Step 2: Create two Submit buttons (GET and POST buttons) to send data to a script using
respective GET and POST methods.

Step 3: Display the Employee Information received through form.

ER/CORP/CRS/LA82/5

Version No. 1.0

28 of 29

Infosys Technologies Limited

Lab Guide for Perl Scripting

Step 4: Display the Environmental Variables (%ENV) and identify the changes in both cases.
Summary of this assignment:
Understanding the working of GET and POST methods

Assignment 7: Understanding use of cookies in Perl


Objective: To understand how to use cookies in Perl
Problem Description: to create web page and get and set cookies to the page
Estimated time: 15 minutes
Step 1: Create Guestbook.pl similar to Assignment-5
Step 2: Modify Guestbook.pl to use cookies to check user gave comments and display a
message accordingly
Step 2.1: Set Cookie in Guestbook.pl with following details:
Cookie name: guest_entry
Cookie-value: given
Cookie-expires: 1 day
Step 2.2: Receive and check cookies to display
(i)
Comments already given!! Thank You. if cookie is already set
(ii)
Display GuestBook form if cookie is not set.

Summary of this assignment:


Understanding the implementation of Cookies through cgi.pm

Assignment 8: Understanding Implementation CGI and Database


Objective: To understand how to implement CGI and Database connectivity together
Problem Description: to create web page to display details of employee received
from Employee Database (Oracle)
Estimated time: 15 minutes
Step 1: Create a form to enter employee number.
Step 2: Connect to database to fetch the employee details with entered employee
number.
Step 3: Create a tabular report (Web Page) to display the fetched details.
Summary of this assignment:
Understanding the implementation Database Operations and web pages

ER/CORP/CRS/LA82/5

Version No. 1.0

29 of 29

S-ar putea să vă placă și