S R SW TI: College of Engineering
S R SW TI: College of Engineering
S R SW TI: College of Engineering
Collegeofof
Department of Computer Engineering Engineering
Engineering
Saraswati College of Engineering, Kharghar
Vision:
Mission:
To educate students to become quality technocrats for taking up challenges in all facets of life.
Vision:
To imprint knowledge to our students to excel in engineering culture and research and nurture
them to become ethically rich professionals.
Mission:
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
NAVI MUMBAI, KHARGHAR.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
1. To prepare the candidate for a successful career in the industry and make him
acquainted with the latest software and hardware,
2. To enable student to work productively as computer engineers, including supportive
teamwork and leadership roles on multidisciplinary teams,
3. Graduates are prepared to be responsible computing professionals in their own area of
interest,
4. To provide the candidate with a sound foundation in mathematics, software
technologies, database technologies, networking, hardware and to prepare them for post
graduate studies and research programs,
5. To promote the awareness of lifelong learning among students and to introduce them to
professional ethics and codes of professional practice,
6. To demonstrate effective communication skills in oral, written and electronic media.
Course Outcomes:
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. To develop program for data structure using built in functions in python.
4. To explore django web framework for developing python based web application.
6. To explore basics of two way communication between client and server using python and perl
Content:
1 Python basics Data types in python ,Operators in python, Input and Output, Control
6 Perl advanced Working with Files, Data manipulation, Database Systems, Networking
Text Books
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
1. Core Python Programming, Dr. R. Nageswara Rao, Dreamtech Press
2. Beginning Python: Using Python 2.6 and Python 3.1. James Payne, Wrox publication
Reference Book
2. Learn Python the Hard Way: (3rd Edition) (Zed Shaw's Hard Way Series)
Digital Material:
3. http://spoken-tutorial.org
4. www.staredusolutions.org
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
SARASWATI COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
LIST OF EXPERIMENTS
Sr no. Experiment
1 Program to swap two numbers and check if first number is positive or
negative or zero.
C. Update first element with x value and delete middle element of list.
E. Add n names into the existing number list and check if word python is
present in list.
A. Add and show N student roll number, name and 3 subject marks in a list
of tuples.
C. Display letters which are in the first string but not in the second.(set
difference)
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
D. Display set of all letters of both the strings.(set union)
E. Displays letters which are in the two strings but not in both.(symmetric
difference)
9 Exception handling
B. Program to append data to existing file and then display entire file.
11 Create a package and module for data structure :stack and queues.
12 Creation of simple socket for basic info exchange between server and client.
13 A. Perl script to find a factorial of a number using for and until loop if the
number is even number.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
14 Design a class person and create its objects in perl.
H/W Requirement P-IV and above, Ram 128 MB, Printer, Internet Connection
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 1
Aim: Program to swap two numbers and check if first number is positive or negative or
zero
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE
The first two are called interactive modes where we can type the program one line at a time
and the complier executes it immediately. The last one is called non-interactive mode where we
ask complier to execute our program after typing the entire program. Programmers can store
Python script source code in a file with the ’.py’ extension, and use the interpreter to execute
the contents of the file. To execute the script by the interpreter, you have to tell the interpreter
the name of the file. Decision making is required when we want to execute a code only if a
certain condition is satisfied. The if…elif…else statement is used in Python for decision
making. Syntax for if statement as follows:
1. if expression:
2. if expression:
else:
3. if expression:
elif expression:
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
//execute your code
else:
Conclusion: We have studied how to run python program and swapping of two number,
control statement if else for find the given number is positive, negative or zero .
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 2
Aim: Menu driven program to check if number and string is palindrome and find factorial of
input number.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.
1. Use the keyword def to declare the function and follow this up with the function name.
2. Add arguments to the function: they should be within the parentheses of the function. End
your line with a colon.
4. End your function with a return statement if the function should output something. Without
the return statement, your function will return an object None.
5. docstring is short for documentation string. It is used to explain in brief, what a function
does.
def function_name(parameters):
"""docstring"""
statement(s)
A palindrome is a string which is same read forward or backwards. For example: "dad" is the
same in forward or reverse direction. Another example is "aibohphobia" which literally means,
an irritable fear of palindromes. The factorial of a number is the product of all the integers
from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Factorial is not defined for negative numbers and the factorial of zero is one, 0! = 1.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: We have studied how to write functions in python program to find palindrome
and factorial of number.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 3
Aim: Write a Menu driven program to demonstrate use of list in python.
C. Update first element with x value and delete middle element of list.
E. Add n names into the existing number list and check if word python is present in list.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, python IDLE.
Theory: Lists are positionally ordered collections of arbitrarily typed objects, and they have no
fixed size and they are mutable. Lists are contained in square brackets []. Lists can contain
numbers, strings, nested sublists, or nothing
Examples: L1 = [0,1,2,3],
L2 = ['zero', 'one'],
L3 = [0,1,[2,3],'three',['four,one']],
L4 = [].
List indexing works just like string indexing. Lists are mutable: individual elements can be
reassigned in place. Moreover, they can grow and shrink in place.
Example:
>>> L1 = [0,1,2,3]
>>> L1[0] = 4
>>> L1[0]
Basic List Operations Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list, not a string. Some of
basic operations of list are as follows.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Python includes the following list functions –
Sr No Function Description
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: Hence from above experiment student can understand that basic concept of list
and list related various operation that create the list ,update the list, merge the list etc.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 4
Aim: Menu driven program to demonstrate use of tuples in python.
A. Add and show N student roll number, name and 3 subject marks in a list of tuples.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.
Theory: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as
putting different comma-separated values. Optionally you can put these comma-separated
values between parentheses also. For example
tup2 = (1, 2, 3, 4, 5 );
However, there are certain advantages of implementing a tuple over a list. Below listed are
some of the main advantages:
We generally use tuple for heterogeneous (different) datatypes and list for
homogeneous (similar) datatypes.
Since tuple are immutable, iterating through tuple is faster than with list. So there is a
slight performance boost.
Tuples that contain immutable elements can be used as key for a dictionary. With list,
this is not possible.
If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.
1. Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by
comma. The parentheses are optional but is a good practice to write it. A tuple can have any
number of items and they may be of different types (integer, float, list, string etc.).
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
2. Accessing Elements in a Tuple There are various ways in which we can access the
elements of a tuple.
a. Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element
other that (6, 7,...) will raise an IndexError. The index must be an integer, so we cannot use
float or other types. This will result into TypeError.
b. Negative Indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
c. Changing a Tuple
Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed
once it has been assigned. But, if the element is itself a mutable datatype like list, its nested
items can be changed.
d. Python Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
Method Description
Conclusion: Hence from this experiment we learned the various functions of tuples like delete,
modify or insert elements of tuples since tuple are immutable, so for that how to create a new
tuple and store the updated elements in it.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 5
Aim: Write a menu driven program to demonstrate use of set in python
C. Display letters which are in the first string but not in the second (set difference)
E. Displays letters which are in the two strings but not in both (symmetric difference)
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.
Theory: A Set is an unordered collection data type that is iterable, mutable and has no
duplicate elements. Python’s set class represents the mathematical notion of a set. The major
advantage of using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set. This is based on a data structure
known as a hash table.
2. union(s) Method: Returns a union of two set. Using the ‘|’ operator
between 2 sets is the same as writing set1.union(set2)
Conclusion: Hence from this experiment we learned the various operations of sets in python.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 6
Aim: Menu driven program to demonstrate use of dictionary in python
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE.
In the above example: A dictionary is created. This dictionary contains three elements.
Each element constitutes of a key value pair. This dictionary can be accessed using the
variable myDict.
2. Access Dictionary Elements Once a dictionary is created, you can access it using the
variable to which it is assigned during creation. For example, in our case, the variable
myDict can be used to access the dictionary elements. Here is how this can be done :
>>> myDict["A"]
'Apple'
>>> myDict["B"]
'Boy'
>>> myDict["C"]
'Cat'
So you can see that using the variable myDict and Key as index, the value of
corresponding key can be accessed. For those who have C/C++ background, it’s more
like accessing the value kept at a particular index in an array. If you just type the name
of the variable myDict, all the key value pairs in the dictionary will be printed.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Only dictionary keys can be used as indexes. This means that myDict[“A”] would
produce ‘Apple’ in output but myDict[“Apple”] cannot produce ‘A’ in the output.
>>> myDict["Apple"]
Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'Apple'
So we see that the python compiler complained about ‘Apple’ being used as index.
3. Update Dictionary Elements Just the way dictionary values are accessed using keys,
the values can also be modified using the dictionary keys. Here is an example to
modify python dictionary element:
>>> myDict
You can see that in the example shown above, the value of key ‘A’ was changed from
‘Apple’ to ‘Application’ easily. This way we can easily conclude that there could not be
two keys with same name in a dictionary.
>>> myDict
So you can see that by using ‘del’ an element can easily be deleted from the dictionary.
If you want to delete complete dictionary i.e all the elements in the dictionary then it
can be done using the clear() function. Here is an example :
>>> myDict.clear()
>>> myDict
{}
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
So you see that all the elements were deleted making the dictionary empty.
>>> myDict
You can observe that the order of elements while the dictionary was being created is
different from the order in which they are actually stored and displayed.
>>> myDict
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog'}
You’ll observe that it’s not necessary that elements will be stored in the same order in
which they were created.
2. Dictionary Keys are Case Sensitive. Same key name but with different case are
treated as different keys in python dictionaries. Here is an example :
>>> myDict
{'A': 'Apple', 'C': 'Cat', 'B': 'Boy', 'E': 'Elephant', 'D': 'Dog', 'F': 'Fan', 'f'’: ‘freeze '}
Conclusion: Hence from this experiment we learned the various operation of dictionary like
create, modify or insert elements of dictionary and how two lists can merge in the dictionary.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 7
Aim: Design an employee class using python for reading and displaying the employee
information.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE
Theory:
Creating Classes:
The class statement creates a new class definition. The name of the class immediately follows
the keyword class followed by a colon as follows –
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data
attributes and functions.
To create instances of a class, you call the class using class name and pass in whatever
arguments its __init__ method accepts.
Accessing Attributes
You access the object's attributes using the dot operator with object.
Conclusion: Hence from this experiment we learned how to create classes and its objects in
python.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 8
Aim: Program to demonstrate single and multiple inheritance in python (with method
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3
Theory:
2. Multiple Inheritances: A derived class with several base classes is called Multiple
Inheritance.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. Hierarchical Inheritance: More than one class may inherit the features of one class this
process is called as Hierarchical Inheritance.
4. Multilevel Inheritance: The mechanism of deriving a class from another derived class is
5. Hybrid Inheritance: There could be situations where we need to apply one or more types
of inheritances to design a program this process is called Hybrid Inheritance.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Method overloading: In Python you can define a method in such a way that there are multiple
ways to call it. Given a single method or function, we can specify the number of parameters
ourselves. Depending on the function definition, it can be called with zero, one, two or more
parameters. This is known as method overloading.
if a is not None:
else:
obj = operation()
obj.abc ()
obj.abc('10')
Example
class Parent(object):
def __init__(self):
self.value = 5
return self.value
class Child(Parent):
def get_value(self):
return self.value + 1
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: From this experiment we studied how to write a class and use the concept of
inheritance to achieve the specified requirements.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 9
Aim: Exception handling
A. Write a program to demonstrate exception handling using try, multiple exception and
finally.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3
Theory:
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them:
a. Exception Handling
b. Assertions
2 StandardError Base class for all built-in exceptions except StopIteration and
SystemExit.
3 ArithmeticError Base class for all errors that occur for numeric calculation.
6 IOError Raised when an input/ output operation fails, such as the print
statement or the open() function when trying to open a file that
does not exist.
8 ValueError It is raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid values
specified.
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: From this experiment we studied how to use standard exceptions and create user
defined exceptions in python.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 10
Aim: Exploring files and directories.
A. Python program to read the content of file and write in another file.
B. Program to append data to existing file and then display entire file.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Python IDLE3
Theory:
Data is very important. Every organization depends on its data for continuing its business
operations. To store the data in computer we need files. There are certain advantages of storing
data in file:
a. to store huge amount of data When data is stored in a file, it is stored permanently.
It is very important to know how to create files, store data in the files and retrieve the data
from the files in python. To do any operations on files, first of all we should open the files.
Opening a File in order to open a file for writing or use in Python, you must rely on the built-in
open () function.
As explained above, open ( ) will return a file object, so it is most commonly used with two
arguments. An argument is nothing more than a value that has been provided to a function,
which is relayed when you call it. So, for instance, if we declare the name of a file as “Test
File,” that name would be considered an argument. The syntax to open a file object in Python
is:
file_object = open(“filename”, “mode”) where file_object is the variable to add the file object.
Mode Including a mode argument is optional because a default value of ‘r’ will be assumed if
it is omitted. The ‘r’ value stands for read mode, which is just one of many. The modes are:
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
‘r’ – Read mode which is used when the file is only being read
‘w’ – Write mode which is used to edit and write new information to the file (any existing
files with the same name will be erased when this mode is activated)
‘a’ – Appending mode, which is used to add new data to the end of the file; that is new
information is automatically amended to the end
‘r+’ – Special read and write mode, which is used to handle both actions when working with
a file.
f=open(“workfile”,”w”)
Print f
This snippet opens the file named “workfile” in writing mode so that we can make changes to
it. Just create the file named “testfile.txt” and leave it blank. If you need to extract a string that
contains all characters in the file, then
file=open(“testfile.text”, “r”)
print file.read()
Using the File Write Method the file write method is that it only requires a single parameter,
which is the string you want to be written. This method is used to add information or content to
an existing file. To start a new line after you write data to the file, you can add an EOL
character. Closing a File when you’re done working, you can use the fh.close() command to
end things.
Conclusion: Hence from above experiment student will understand various file operations like
creation of file, storing data in the files and retrieve data from the files in python.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 11
Aim: Program to create a package and module for data structures like stack and queues.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, PYTHON IDLE3
Theory:
Stack
It is a sequence of items that are accessible at only one end of the sequence. Think of a stack as
a collection of items that are piled one on top of the other, with access limited to the topmost
item. A stack inserts item on the top of the stack and removes item from the top of the stack. It
has LIFO (last-in / first-out) ordering for the items on the stack. Also, the inbuilt functions in
Python make the code short and simple. To add an item to the top of the list, i.e., to push an
item, we use append() function and to pop out an element we use pop() function. These
functions work quiet efficiently and fast in end operations.
Queue
A queue is a sequential storage structure that permits access only at the two ends of the
sequence. We refer to the ends of the sequence as the front and rear. A queue inserts new
elements at the rear and removes elements from the front of the sequence. You will note that a
queue removes elements in the same order in which they were stored, and hence a queue
provides FIFO (first-in / first-out), or FCFS (first-come / first-served), ordering. Implementing
queue is a bit different. Time plays an important factor here. During the implementation of
stack we used append() and pop() function which was efficient and fast because we inserted
and popped elements from the end of the list, but in queue when insertion and pops are made
from the beginning of the list, it is slow. This occurs due to the properties of list, which is fast
at the end operations but slow at the beginning operations, as all other elements have to be
shifted one by one. So, it’s preferable to use collections.deque over list, which was specially
designed to have fast appends and pops from both the front and back end.
Conclusion: From this experiment we have studied built in functions like pop(), append() used
to perform operations on data structures like stack and queue.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 12
Aim: Program to create simple socket for basic info exchange between server and client.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, PYTHON IDLE3
Theory:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET
and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4.
The SOCK_STREAM means connection oriented TCP protocol. Now we can connect to a
server using this socket.
Connecting to a server:
Note that if any error occurs during the creation of a socket then a socket.error is thrown and
we can only connect to a server by knowing its IP.
You can find the ip of the server by using this: $ ping www.google.com
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Server Socket Methods
Method Description
Method Description
Server :
A server has a bind() method which binds it to a specific ip and port so that it can listen to
incoming requests on that ip and port. A server has a listen() method which puts the server into
listen mode. This allows the server to listen to incoming connections. And last a server has an
accept() and close() method. The accept method initiates a connection with the client and the
close method closes the connection with the client.
Client :
Now we need something with which a server can interact. We could tenet to the server like this
just to know that our server is working. Type these commands in the terminal: # start the server
$ python server.py # keep the above terminal open # now open another terminal and type: $
telnet localhost 12345
Conclusion: From this experiment we studied the client server communication on a network
with the help of socket.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 13
Aim: A. Write a Perl script to find a factorial of a number using for and until loop if the
number is even number.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl
Theory:
Perl Installation:
The most up-to-date and current source code, binaries, documentation, news, etc. are available
at the official website of Perl. Perl Official Website − https://www.perl.org/ download only the
binary code applicable for your platform and install Perl. The following are the different ways
to start Perl:
1. Interactive Interpreter You can enter perl and start coding right away in the interactive
interpreter by starting it from the command line.
or
2. Script from the Command-line A Perl script is a text file, which keeps perl code in it
and it can be executed at the command line by invoking the interpreter on your
application, as in the following –
or
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
3. Integrated Development Environment
You can run Perl from a graphical user interface (GUI) environment as well. All you
need is a GUI application on your system that supports Perl.
Arrays
An array is a variable that stores an ordered list of scalar values. Array variables are preceded
by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($)
with the variable name followed by the index of the element in square brackets.
Hashes
A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer
to a single element of a hash, you will use the hash variable name preceded by a "$" sign and
followed by the "key" associated with the value in curly brackets.
Creating Hashes
2. use a list, which is converted by taking individual pairs from the list: the first
element of the pair is used as the key, and the second, as the value.
{ statement(s); }
2. until loop: An until loop statement in Perl programming language repeatedly executes a
target statement as long as a given condition is false.
until(condition)
{ statement(s);}
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Conclusion: From this experiment we have studied creation and insertion of array and hashes
in Perl. We have used the until and for loop structure in perl to find the factorial of a number.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 14
Aim: Write a Perl script to design a class person and create its objects in Perl
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl
Theory: In Perl, a class is corresponds to a Package. To create a class in Perl, we first build a
package. A package is a self-contained unit of user-defined variables and subroutines, which
can be re-used over and over again. They provide a separate namespace within a Perl program
that keeps subroutines and variables from conflicting with those in other packages.
package Person;
The scope of the package definition extends to the end of the file, or until another package
keyword is encountered.
Creating and Using Objects: To create an instance of a class (an object) we need an object
constructor. This constructor is a method defined within the package. Most programmers
choose to name this object constructor method new, but in Perl one can use any name.
One can use any kind of Perl variable as an object in Perl. Most Perl programmers choose
either references to arrays or hashes.Using a Perl hash reference when creating an object, you
need to supply a constructor. This is a subroutine within a package that returns an object
reference. The object reference is created by blessing a reference to the package's class. Every
method of a class passes first argument as class name.
Conclusion: From this experiment we have studied creation of class and objects in perl.
By Student -______________________________________________________
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
Experiment 15
Aim: Write a PERL program to demonstrate.
Hardware and Software Requirement: P-IV and above, Ram 128 MB, Perl
Theory:
Opening a File: To open a file to be read by Perl, you need to use the open function with a
filehandle. The syntax for open is:
where handle is the filehandle and filename is the file to be opened, which may include a path.
If you do not specify a directory path, the current directory is assumed. Normally you will
embed an open function inside an if statement to make sure the file was opened properly.
Otherwise, commands later in the program would cause errors. Here’s a typical setup:
{statements to run}
Else
Closing a File - After you have opened a file and done something with it, you should always
close the file. Closing the file lets the operating system know the file is not in use anymore and
the filehandle is freed.
To close a filehandle, use the close function with the handle name:
statements…
close BIGFILE;
Reading a File –
SɅRɅSWɅTI
SɅRɅSWɅTI College
Collegeofof
Department of Computer Engineering Engineering
Engineering
There are a couple of ways to read from an open filehandle. The most common is to use the file
input operator, which is a pair of angle brackets around the filehandle name (just like
<STDIN> to read from the keyboard).
For example:
This will read a line from the file data.txt (referred to by the filehandle and not the name) and
store it in $line.
The line $line=<MFILE>; will read a whole line of input from the MFILE filehandle.
If there is nothing to read, the value “undef” (for undefined) is returned. You can use loops to
read through an entire file.
To test whether the value undef has been detected, use the “defined” keyword:
while(defined($line=<MFILE>))
…
Regular Expressions –
A regular expression is a string of characters that defines the pattern or patterns you are
viewing. The syntax of regular expressions in Perl is very similar to what you will find within
other regular expression supporting programs, such as sed, grep, and awk.
The match operator, m//, is used to match a string or statement to a regular expression.
Conclusion: From this experiment we have studied create and read operation on file in Perl.
We have used file handle to read data from file and write data to the file. We also studied how
to match regular expressions and substitute regular expressions.
By Student -______________________________________________________
SɅRɅSWɅTI