[go: up one dir, main page]

0% found this document useful (0 votes)
16 views38 pages

Oss Unit5 Up

The document provides an overview of the Perl programming language, including its history, features, and applications. It outlines the learning objectives and course outcomes for a college course on Open Source Software, specifically focusing on Perl as a scripting language for web development and data manipulation. Additionally, it covers Perl's syntax, variable types, and advantages and disadvantages, along with practical examples and resources for further learning.

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views38 pages

Oss Unit5 Up

The document provides an overview of the Perl programming language, including its history, features, and applications. It outlines the learning objectives and course outcomes for a college course on Open Source Software, specifically focusing on Perl as a scripting language for web development and data manipulation. Additionally, it covers Perl's syntax, variable types, and advantages and disadvantages, along with practical examples and resources for further learning.

Uploaded by

then mozhi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

MARUDHAR KESARI JAIN COLLEGE FOR WOMEN (AUTONOMOUS)

VANIYAMBADI
PG and Department of Computer Applications
III BCA – Semester – VI
E-Notes (Study Material)

Core Course -1: Open Source Software Code:FCA61

UNIT V: PERL
PERL: Perl background-Perl overview-Perl parsing rules-Variables and Data-Statement and Control
structure- Subroutine, packages and Modules-Working with Files-Data Manipulation.
Learning Objectives:
1.To understand the concept of HTML, HTML5 and CSS.
2.To understand the concept of scripting code for a website.
3.To understand the concept of scripting code for a website.
4.To understand the fundamentals of PHP language combined with HTML.
5.To understand the fundamentals of PERL languages.

Course Outcome:
1.The student will be able to understand the concept of HTML, HTML5 and CSS.
2.The student will be able to learn to inspect and detect errors by going through each and every code
segment.
3.The student will be able to understand basic concept of Java script and MYSQL.
4.The student will be able to understand basic concept of PHP.
5.The student will be able to understand basic concept of PERL.

1. PERL: Perl background-Perl overview:


PERL Introduction:
PERL is a general-purpose, high level interpreted and dynamic programming language. It was
developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most
used expansion is “Practical Extraction and Reporting Language“. Some of the programmers also
refer Perl as the “Pathologically Eclectic Rubbish Lister” Or “Practically Everything Really
Likable“.
The acronym “Practical Extraction and Reporting Language” is used widely because Perl was
originally developed for the text processing like extracting the required information from a
specified text file and for converting the text file into a different form. Perl supports both the
procedural and Object-Oriented programming.
Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++.
Evolution of Perl: It all started when Larry Wall was working on a task to generate the reports
from a lot of text files which have cross-references. Then he started to use awk for this task but
soon he found that it is not sufficient for this task. So instead of writing a utility for this task, he
wrote a new language i.e. Perl and also wrote the interpreter for it.
He wrote the language Perl in C and some of the concepts are taken from awk, sed, and LISP etc.
At the beginning level, Perl was developed only for the system management and text handling
but in later versions, Perl got the ability to handle regular expressions, and network sockets etc.

1
In present Perl is popular for its ability to handling the Regex(Regular Expressions). The first
version of Perl was 1.0 which released on December 18, 1987. The latest version of Perl is 5.28.
Perl 6 is different from Perl 5 because it is a fully object-oriented reimplementation of Perl 5.

Perl is a high-level, general-purpose programming language that was created by Larry Wall in
1987. It was originally designed for text processing, but has since evolved to become a full-
featured programming language that is widely used in web development, system administration,
network programming, and more.

Perl is a popular choice for many programmers because of its versatility and powerful regular
expression support, which makes it ideal for text processing and data manipulation tasks. It also
has a large and active community of developers who have contributed to a vast library of modules
and extensions that can be used to extend the language’s functionality.

One of Perl’s defining features is its “There’s more than one way to do it” philosophy, which
encourages developers to solve problems using their own preferred methods rather than adhering
to strict coding conventions. This can make Perl code more flexible and expressive, but it can also
lead to code that is difficult to read and maintain.

Perl code is typically interpreted, meaning that it is executed directly by the computer without the
need for compilation. This can make development faster and more flexible, but can also lead to
slower execution times for large programs. However, Perl also supports compilation through tools
such as Perlcc and Parrot, which can help to improve performance for larger projects.
Perl Background:
Perl has many reasons for being popular and in demand. Few of the reasons are mentioned below:
Easy to start: Perl is a high-level language so it is closer to other popular programming languages
like C, C++ and thus, becomes easy to learn for anyone.
Text-Processing: As the acronym “Practical Extraction and Reporting Language” suggest that Perl
has the high text manipulation abilities by which it can generate reports from different text files
easily. Also, it can convert the files into some another form.
Contained best Features: Perl contains the features of different languages like C, sed, awk, and sh
etc. which makes the Perl more useful and productive.
System Administration: Due to having the different scripting languages capabilities Perl make the
task of system administration very easy. Instead of becoming dependent on many languages, just
use Perl to complete out the whole task of system administration. In Spite of this Perl also used
in web programming, web automation, GUI programming etc.
Web and Perl: Perl can be embedded into web servers to increase its processing power and it has
the DBI package, which makes web-database integration very easy.

2
2.PERL overview:
Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk,
Lisp and even English. However, there are some definite differences between the languages. This
chapter is designed to quickly get you up to speed on the syntax that is expected in Perl.
A Perl program consists of a sequence of declarations and statements, which run from the top to
the bottom. Loops, subroutines, and other control structures allow you to jump around within the
code. Every simple statement must end with a semicolon (;).
Perl is a free-form language: you can format and indent it however you like. Whitespace serves
mostly to separate tokens, unlike languages like Python where it is an important part of the syntax,
or Fortran where it is immaterial.
First Perl Program
Interactive Mode Programming
You can use Perl interpreter with -e option at command line, which lets you execute Perl
statements from the command line. Let's try something at $ prompt as follows −
$perl -e 'print "Hello World\n"'
This execution will produce the following result −
Hello, world

Perl advantages :
* It is more flexible to use.
* Its syntax is simple, which makes it easy to understand.
* It supports OOP concepts.
* Perl programs run easily on the system.
* It supports all platforms and is much more portable.
* It has a rich set of Perl modules and free software.
* It is much more efficient to work on text and string manipulation as it is a scripting language.
* Perl combines features of many other languages which make it easy to understand.

Perl disadvantages :
* A Perl program containing CPAN modules will not run on another system which doesn't have
CPAN modules installed.
* It is an interpretative language, so it is slower in comparison with other languages.
* It has untidy and unreadable codes.
* It starts creating problems when the code is larger than 200 lines.

3
* It is not portable.
 Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among
others.
 Perl's database integration interface DBI supports third-party databases including Oracle,
Sybase, Postgres, MySQL, and others.
 Perl works with HTML, XML, and other mark-up languages.
 Perl supports Unicode.
 Perl is Y2K compliant.
 Perl supports both procedural and object-oriented programming.
 Perl interfaces with external C/C++ libraries through XS or SWIG.
 Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network (CPAN).
 The Perl interpreter can be embedded into other systems.
Perl Features
The following list of features are available in Perl and are broadly adopted from other
programming and
scripting languages:
Perl gets most of its features from C, including variables, expressions, statements, control
structures, and subroutines
It also borrows features from shell scripting for identifying data types. unambiguously, like
an array, scalar, hash, through leading sigils
Perl also has inbuilt functions which are often used in shell programming, such as sort and
system facilities utilization
Perl5 also has added features to support complex data structures and an object-oriented
programming model that includes packages, references, and directives for the compiler
All of the versions of Perl include auto data typing and memory management; the interpreter
understands storage and memory requirements for each data type, allocates, and deallocates
memory based on usage
It also does typecast during the run time like converting an integer to string etc. and other
conversions, which are not legitimate, that are thrown out as errors during execution
Perl doesn’t enforce or recommend any particular programming technique like procedural,
object oriented, or functional—the interpreter, along with its functions, stands as a single
specification of the language
Perl comes with powerful utilities (APIs) for text manipulation that are useful for working
with XML, HTML, and other markup languages
Perl has the highest level of security and is even certified by a third-party security organization
called Coverity, with low defect density and fewer security flaws

4
Perl is also extendable and provides libraries to support XML and integration to databases
including Oracle and MySQL
Applications of Perl
Perl is popular among programmers, along with other programming languages like PHP and
Python. In earlier days, programmers used Perl to write CGI scripts.
Perl is often used as a departmental glue between multiple systems that are not homogenous
or allowed to interoperate seamlessly.
The system administers love this language as they can enter a single command to accomplish
a goal that otherwise would require a program to be written. Perl is mainly portable, with
some degree of customizations between Windows and macOS.
Developers also use the language to build and deploy. It is used by most of the suppliers or
software manufacturers to package and deploy the software commercially (including COTS
and bespoke). It is widely used in the field of finance and bioinformatics due to its ability to
handle and process large volume data sets.
Perl Implementation
Perl is an interpreted language, as mentioned above, written in C with an extensive collection
of modules written in both C and Perl. The Perl interpreter is a whopping 150,000 lines of C
code, which compiles to 1 MB on most of the system architecture.
There are more than 500 modules in Perl distribution with 300, 000 lines of code in Perl and
200,000 lines of code in C.
The interpreter is based on the object oriented architecture in which the elements of Perl
(arrays, scalars, and hashes) are represented as C structures.
The interpreter passes through two phases in its life cycle compile and run phase. At compile
time, the interpreter parses the Perl code into a syntax tree. At run time, it runs the Perl
program by moving along the tree.
Perl language is distributed as open source with 120,000 functional tests; it runs during the
build process and extensively tests the interpreter and other functional modules. If your
changes pass all of these 120K functional tests, you can safely assume that your code will not
break the interpreter.
Additional Resources:
https://www.geeksforgeeks.org/perl-file-handling-introduction/

Practice Questions:
What does "Perl" stand for?
Who developed Perl, and when was it created?
Mention two key features of Perl.
What is the file extension used for Perl scripts?
Is Perl case-sensitive?
Name two common uses of Perl.
5
What is CPAN in Perl?
Which command is used to execute a Perl script?
What is the latest stable version of Perl?
How do you print "Hello, World!" in Perl?

2.Variables and Data:


Variables and Types
Perl is a case-sensitive programming language like UNIX. Perl variables always start with $,
@, or %,
followed by zero, letters, or other digits, supporting three variable types (namely Scalars,
Arrays, and
Hashes). There are no Boolean data types in Perl, and assignment operation is carried out
using = sign.
# sign starts with the comment.

Scalars – These variables contain a single string or numeric value and the variable name
should start
with $
$item_name = “Orange”

Arrays – These variables are ordered sets of values and are prefixed with @
@item_name=(“Orange”, “Grape”, “Lemon”)

Hashes – these are key-value pairs, and they are prefixed with %
%item_catalog = ("Orange" => 5 , "Grape" => 8, "Lemon” => 24);
Creating Variable:
The reserved memory locations to store values are the Variables. This means that creating a
variable, reserves a space in memory. Data type of a variable helps the interpreter to allocate
memory and decide what to be stored in the reserved memory. Therefore, variables can store
integers, decimals, or strings with the assignment of different data types to the variables.
Perl has the following three basic data types namely –
 Scalars
 Arrays
 Hashes
Hence, three types of variables will be used in Perl. A scalar variable can store either a number,
a string, or a reference and will precede by a dollar sign ($). An array variable will store
6
ordered lists of scalars and precede by @ sign. The Hash variable will be used to store sets of
key/value pairs and will precede by sign %.

Creating Variables
Perl variables need not to be declared explicitly to reserve memory space. Just like other
programming languages, the operand to the left of the ‘=’ operator is basically the name of the
variable, and the operand to the right of the ‘=’ operator is basically the value stored in the
variable.
For example:
$age = 40;
$name = “XYZ”;
$rollno = 22;
Here 40, “XYZ” and 22 are the values assigned to $age, $name and $roll no variables,
respectively.
Scalar Variables
A scalar is a single unit of data. It is possible that the data might be an integer number, floating
point, a character, a string, a paragraph, or an entire web page. Here is an example of using
scalar variables
 Perl

#!/usr/bin/perl

# Assigning values to scalar


# variables
$age = 40;
$name = "XYZ";
$rollno = 22;

# Printing variable values


print "Age = $age\n";
print "Name = $name\n";
print "Roll no = $rollno\n";

Output:
Age = 40

7
Name = XYZ
Roll no = 22
Array Variables
Variable that stores an ordered list of scalar values is of array type. Variables of Array Datatype
are preceded by an “at” (@) sign. The dollar sign ($) is used to refer a single element of an array
with the variable name followed by the index of the element in square brackets.
Here is an example of how to use an array variable:
 Perl

#!/usr/bin/perl

# Assigning values to Array variables


@ages = (55, 80, 44); # @ is used to declare
# array variables
@names = ("XYZ", "LGH", "KMR");

# Printing values of Arrays


print "\$ages[0] = $ages[0]\n";
print "\$ages[1] = $ages[1]\n";
print "\$ages[2] = $ages[2]\n";
print "\$names[0] = $names[0]\n";
print "\$names[1] = $names[1]\n";
print "\$names[2] = $names[2]\n";

Hash Variables
A hash is a set of key/value pairs. Variables of the Hash type are preceded by a modulus (%) sign.
Keys are used to refer to a single variable in the Hash. To access these elements, Hash variable
name followed by the Key associated with the value is used in curly brackets.
Following is a simple example to show Hash Variable:
 Perl

8
#!/usr/bin/perl

# Defining Hash variable using '%'


%data = ('XYZ', 55, 'LGH', 80, 'KMR', 44);

# Printing values of Hash variables


print "\$data{'XYZ'} = $data{'XYZ'}\n";
print "\$data{'LGH'} = $data{'LGH'}\n";
print "\$data{'KMR'} = $data{'KMR'}\n";

Output:
$data{'XYZ'} = 55
$data{'LGH'} = 80
$data{'KMR'} = 44

Variable Context
Based on the Context, Perl treats the same variable differently i.e., situation where a variable is
being used.
Example:
 Perl

#!/usr/bin/perl

# Defining Array variable


@names = ('XYZ', 'LGH', 'KMR');

# Assigning values of array variable


# to another array variable
@copy = @names;

# Assigning values of Array variable


# to a scalar variable

9
$size = @names;

# Printing the values of new variables.


print "Given names are : @copy\n";
print "Number of names are : $size\n";

Output:
Given names are : XYZ LGH KMR
Number of names are : 3
Additional Resources:
https://how.dev/answers/what-are-packages-and-modules-in-perl
Practice Questions:
2-Mark Questions
1. What are the three main types of variables in Perl?
2. How do you declare a scalar variable in Perl? Provide an example.
3. What is the difference between an array and a hash in Perl?
4. How do you retrieve the size of an array in Perl?
5. What does the special variable $_ represent in Perl?
5-Mark Questions
6. Explain scalar, array, and hash variables with examples.
7. How do you create and access elements in a hash in Perl? Provide an example.
8. What are references in Perl? Explain with an example.
9. Discuss the difference between list and scalar context in Perl.
10. Write a Perl script to store and print the names of five students using an array.
10-Mark Questions
11. Explain arrays in Perl with examples of common operations like adding, removing, and
modifying elements.
12. Describe Perl hashes in detail. Write a script that stores employee IDs and names in a hash
and retrieves them.
13. What are references in Perl? Explain how to create and dereference array and hash references
with examples.
14. Discuss different special variables in Perl and their significance.

10
15. Write a Perl script that takes a list of numbers from the user, stores them in an array, sorts
them, and prints the sorted list.

3.Statement and Control Structures:


Decision Making in programming is similar to decision making in real life. In programming, a certain
block of code needs to be executed when some condition is fulfilled. A programming language uses
control statements to control the flow of execution of the program based on certain conditions. These
are used to cause the flow of execution to advance and branch based on changes to the state of a
program.

Decision Making Statements in Perl :


 If
 If – else
 Nested – If
 if – elsif ladder
if statement
The if statement is same as in other programming languages. It is used to perform basic condition
based task. It is used to decide whether a certain statement or block of statements will be executed
or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Syntax :
if(condition)
{
# code to be executed
}
Note : If the curly brackets { } are not used with if statements then there will be compile time
error. So it is must to use the brackets { } with if statement.
Flowchart :

11
Example :
 Perl

# Perl program to illustrate if statement

$a = 10;

# if condition to check
# for even number
if($a % 2 == 0 )
{
printf "Even Number";

12
}

Output :
Even Number
if – else Statement
The if statement evaluates the code if the condition is true but what if the condition is not true,
here comes the else statement. It tells the code what to do when the if condition is false.
Syntax :
if(condition)
{
# code if condition is true
}
else
{
# code if condition is false
}
Flowchart :

13
Example :
 Perl

# Perl program to illustrate


# if - else statement

$a = 21;

# if condition to check
# for even number
if($a % 2 == 0 )
{
printf "Even Number";
}
else
{
printf "Odd Number\n";
}

Output :
Odd Number

Nested – if Statement
if statement inside an if statement is known as nested if. if statement in this case is the target of
another if or else statement. When more than one condition needs to be true and one of the
condition is the sub-condition of parent condition, nested if can be used.
Syntax :
if (condition1)
{
# Executes when condition1 is true

if (condition2)
{
# Executes when condition2 is true

14
}
}
Flowchart :

Example :
 Perl

# Perl program to illustrate


# Nested if statement

$a = 10;

if($a % 2 ==0)

15
{
# Nested - if statement
# Will only be executed
# if above if statement
# is true
if($a % 5 == 0)
{
printf "Number is divisible by 2 and 5\n";
}
}

Output :
Number is divisible by 2 and 5
If – elsif – else ladder Statement
Here, a user can decide among multiple options. The if statements are executed from the top down.
As soon as one of the conditions controlling the if is true, the statement associated with that get
executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final
else statement will be executed.
Syntax :
if(condition1)
{
# code to be executed if condition1 is true
}
elsif(condition2)
{
# code to be executed if condition2 is true
}
elsif(condition3)
{
# code to be executed if condition3 is true
}
...
else

16
{
# code to be executed if all the conditions are false
}
Flowchart :

if-else-if
Example :
 Perl

# Perl program to illustrate


# if - elseif ladder statement

$i = 20;

17
if($i == 10)
{
printf "i is 10\n";
}

elsif($i == 15)
{
printf "i is 15\n";
}

elsif($i == 20)
{
printf "i is 20\n";
}

else
{
printf "i is not present\n";
}

Output :
i is 20
A while loop in Perl generally takes an expression in parenthesis. If the expression is True then
the code within the body of while loop is executed. A while loop is used when we don’t know the
number of times we want the loop to be executed however we know the termination condition of
the loop. It is also known as an entry controlled loop as the condition is checked before executing
the loop. The while loop can be thought of as a repeating if statement.
Syntax :
while (condition)
{
# Code to be executed
}

18
Flow Chart:

Example :

# Perl program to illustrate


# the while loop

# while loop
$count = 3;
while ($count >= 0)
{
$count = $count - 1;
print "GeeksForGeeks\n";
}

Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
Nested while loop
A Nested while loop is one in which one while loop is used inside another while loop. In a Nested
while loop, for each iteration of the outer while loop, the inner while loop gets executed
completely.

19
#!/usr/bin/perl
# Perl program for Nested while loop
$a = 0;

# while loop execution


while( $a <= 2 )
{
$b = 0;
while( $b <= 2 )
{
printf "$a $b\n";
$b++;
}
$a++;
}

Output:
00
01
02
10
11
12
20
21
22
Infinite While Loop
While loop can execute infinite times which means there is no terminating condition for this loop.
In other words, we can say there are some conditions that always remain true, which causes while
loop to execute infinite times or we can say it never terminates.
Below program will print the specified statement infinite time and also gives the runtime error
as Output Limit Exceeded on online IDE

20
# Perl program to illustrate
# the infinite while loop

# infinite while loop


# containing condition 1
# which is always true
while(1)
{
print "Infinite While Loop\n";
}

Output:
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.
.
Additional Resources:
https://how.dev/answers/what-are-packages-and-modules-in-perl
Practice Questions:
2-Mark Questions (Short Answer)
1. What are the basic control structures available in Perl?
2. How do you write an if statement in Perl?
3. What is the difference between next and last in loops?
4. How does the unless statement work in Perl?
5. What is the purpose of the foreach loop in Perl?
6. How do you write a while loop in Perl?
7. What is the difference between redo and next?
8. How do you use the ternary operator in Perl?
21
9. What is the role of elsif in an if statement?
10. Write a simple example of a for loop in Perl.

5-Mark Questions (Brief Explanations & Small Code Examples)


1. Explain the difference between if, elsif, and else with an example.
2. What are the different types of loops in Perl? Explain with examples.
3. Describe the foreach loop and its usage in iterating over arrays.
4. How does Perl handle nested loops? Provide an example.
5. Explain last, next, and redo with examples.
6. How does Perl handle switch-like behavior since it lacks a switch statement?
7. Write a Perl script to check whether a number is positive, negative, or zero using if-elsif-else.
8. How does the do-while loop work in Perl? Explain with an example.
9. Write a Perl script to print even numbers from 1 to 20 using a for loop.
10. Explain how Perl evaluates boolean expressions in control structures.

10-Mark Questions (Detailed Explanations & Full Programs)


1. Explain all looping constructs in Perl (for, while, until, foreach). Provide examples for each.
2. Write a Perl script to check if a given number is prime using a loop and conditional statements.
3. Discuss the importance of control structures in Perl programming with detailed examples.
4. Write a Perl program to generate the Fibonacci series up to 10 terms using a loop.
5. Explain nested if statements with an example program that categorizes student grades.

4.Function/Subroutines:
A Perl function or subroutine is a group of statements that together perform a specific task. In
every programming language user want to reuse the code. So the user puts the section of code in
function or subroutine so that there will be no need to write code again and again. In Perl, the
terms function, subroutine, and method are the same but in some programming languages, these
are considered different. The word subroutines is used most in Perl programming because it is
created using keyword sub. Whenever there is a call to the function, Perl stop executing all its
program and jumps to the function to execute it and then returns back to the section of code that
it was running earlier. One can avoid using the return statement.
Defining Subroutines: The general form of defining the subroutine in Perl is as follows-
sub subroutine_name
{
# body of method or subroutine

22
}
Calling Subroutines: In Perl subroutines can be called by passing the arguments list to it as
follows-
subroutine_name(aruguments_list);
The above way of calling the subroutine will only work with Perl version 5.0 and beyond. Before
Perl 5.0 there was another way of calling the subroutine but it is not recommended to use because
it bypasses the subroutine prototypes.
&subroutine_name(aruguments_list);
Example:

# Perl Program to demonstrate the


# subroutine declaration and calling

#!/usr/bin/perl

# defining subroutine
sub ask_user {
print "Hello Geeks!\n";
}

# calling subroutine
# you can also use
# &ask_user();
ask_user();

Output:
Hello Geeks!
Passing parameters to subroutines: This is used to pass the values as arguments.This is done
using special list array variables ‘$_’. This will assigned to the functions as $_[0], $_[1] and so
on.
Example:

# Perl Program to demonstrate the


# Passing parameters to subroutines

23
#!/usr/bin/perl

# defining subroutine
sub area
{
# passing argument
$side = $_[0];

return ($side * $side);


}

# calling function
$totalArea = area(4);

# displaying result
printf $totalArea;

Output:
16
Advantage of using subroutines:
 It helps us to reuse the code and makes the process of finding error and debug easy.
 It helps in organizing the code in structural format.Chunks of code is organized in sectional
format.
 It increases the code readability.

Prerequisite: Perl | Subroutines or Functions A Perl function or subroutine is a group of


statements that together perform a specific task. In every programming language, the user wants
to reuse the code. So the user puts the section of code in a function or subroutine so that there will
be no need to rewrite the same code again and again. For this reason, function or subroutine is
used in every programming language. These functions or subroutines can take various different
types of data structures as parameters. Some of these are explained below:
1. Passing Lists or Arrays to a Subroutine
2. Passing References to a Subroutine

24
3. Passing Hashes to a Subroutine
4. Passing File Handles to a Subroutine
Passing Lists or Arrays to a Subroutine: An array or list can be passed to the subroutine as a
parameter and an array variable @_ is used to accept the list value inside of the subroutine or
function. Example 1: Here a single list is passed to the subroutine and their elements are
displayed.
 perl

#!/usr/bin/perl

# Defining Subroutine
sub Display_List
{

# array variable to store


# the passed arguments
my @List1 = @_;

# Printing the passed list elements


print "Given list is @List1\n";
}

# Driver Code

# passing list
@list = (1, 2, 3, 4);

# Calling Subroutine with


# list parameter
Display_List(@list);

Output:
Given list is 1 2 3 4

25
The package statement switches the current naming context to a specified namespace (symbol
table). Thus −
 A package is a collection of code which lives in its own namespace.
 A namespace is a named collection of unique variable names (also called a symbol table).
 Namespaces prevent variable name collisions between packages.
 Packages enable the construction of modules which, when used, won't clobber variables and
functions outside of the modules's own namespace.
 The package stays in effect until either another package statement is invoked, or until the end
of the current block or file.
 You can explicitly refer to variables within a package using the :: package qualifier.
Following is an example having main and Foo packages in a file. Here special variable
__PACKAGE__ has been used to print the package name.
Live Demo
#!/usr/bin/perl

# This is main package


$i = 1;
print "Package name : " , __PACKAGE__ , " $i\n";

package Foo;
# This is Foo package
$i = 10;
print "Package name : " , __PACKAGE__ , " $i\n";

package main;
# This is again main package
$i = 100;
print "Package name : " , __PACKAGE__ , " $i\n";
print "Package name : " , __PACKAGE__ , " $Foo::i\n";

1;
When above code is executed, it produces the following result −
Package name : main 1

26
Package name : Foo 10
Package name : main 100
Package name : main 10
BEGIN and END Blocks
You may define any number of code blocks named BEGIN and END, which act as constructors
and destructors respectively.
BEGIN { ... }
END { ... }
BEGIN { ... }
END { ... }
 Every BEGIN block is executed after the perl script is loaded and compiled but before any
other statement is executed.
 Every END block is executed just before the perl interpreter exits.
 The BEGIN and END blocks are particularly useful when creating Perl modules.
Following example shows its usage −
Live Demo
#!/usr/bin/perl

package Foo;
print "Begin and Block Demo\n";

BEGIN {
print "This is BEGIN Block\n"
}

END {
print "This is END Block\n"
}

1;
When above code is executed, it produces the following result −
This is BEGIN Block
Begin and Block Demo
27
This is END Block

Additional Resources:
https://how.dev/answers/what-are-packages-and-modules-in-perl
Practice Questions:
2-Mark Questions (Short Answer)
1. What is a subroutine in Perl?
2. How do you define a subroutine in Perl?
3. What is @_ used for in a Perl subroutine?
4. How do you return a value from a Perl subroutine?
5. What is the difference between return and implicit return in Perl subroutines?

5-Mark Questions (Brief Explanation & Code)


6. Explain how to pass arguments to a subroutine in Perl with an example.
7. Describe the difference between global and local variables inside a subroutine.
8. What is the purpose of my, local, and our when defining variables in a subroutine?
9. Write a Perl subroutine that takes a list of numbers and returns the sum of all elements.
10. Explain how a subroutine can return multiple values in Perl with an example.

10-Mark Questions (Detailed Explanation & Code)


11. What are the different ways to call a subroutine in Perl? Provide examples for each.
12. Write a Perl subroutine that checks if a given string is a palindrome. Explain the logic.
13. How does Perl handle default values for arguments in subroutines? Write a program
demonstrating this concept.
14. Explain the concept of recursion in Perl with an example of a factorial program.
15. Discuss the difference between subroutines, modules, and packages in Perl. Provide examples.

In Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl
provides a variety of built-in functions and modules that make it easy to work with files. Here’s
an introduction to file handling in Perl:
File modes:
When opening a file in Perl, you need to specify a file mode, which determines how the file can
be accessed. There are three main file modes:
1. Read mode (<): Opens the file for reading. The file must already exist.
28
2. Write mode (>): Opens the file for writing. If the file does not exist, it will be created. If the
file already exists, its contents will be truncated.
3. Append mode (>>): Opens the file for writing, but appends new data to the end of the file
instead of overwriting its contents. If the file does not exist, it will be created.

5.Filehandlingfunctions:
Here are some of the most commonly used built-in file-handling functions in Perl:
1. open(): Opens a file and returns a file handle.
2. close(): Closes a file handle.
3. print(): Writes data to a file.
4. read(): Reads data from a file.
5. seek(): Moves the file pointer to a specific location in the file.
6. tell(): Returns the current position of the file pointer.
7. stat(): Returns information about a file, such as its size, owner, and permissions.
Filehandlingmodules:
In addition to the built-in file-handling functions, Perl also provides a number of modules that can
make file handling easier and more efficient. Here are some of the most commonly used file-
handling modules in Perl:
1. File::Basename: Provides functions for working with file paths, such as extracting the
filename or directory from a path.
2. File::Copy: Provides functions for copying files.
3. File::Find: Provides functions for searching a directory tree for files that match a pattern.
4. File::Path: Provides functions for creating and removing directories.
5. File::Spec: Provides functions for working with file paths that are platform-independent.
Overall, file handling is an important aspect of programming in Perl. Whether you need to read
data from a file, write data to a file, or perform more complex file operations, Perl provides a
variety of tools and modules to help you get the job done.
In Perl, a FileHandle associates a name to an external file, that can be used until the end of the
program or until the FileHandle is closed. In short, a FileHandle is like a connection that can be
used to modify the contents of an external file and a name is given to the connection (the
FileHandle) for faster access and ease.
The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent
Standard Input, Standard Output, and Standard Error devices respectively. File Handling is
usually done through the open function.
Syntax: open(FileHandle, Mode, FileName);
Parameters:
 FileHandle- The reference to the file, that can be used within the program or until its closure.
 Mode- Mode in which a file is to be opened.

29
 FileName- The name of the file to be opened.
Also, Mode and FileName can be clubbed to form a single expression for opening.
Syntax: open(FileHandle, Expression);
Parameters:
 FileHandle- The reference to the file, that can be used within the program or until its closure.
 Expression- Mode and FileName clubbed together.
The FileHandle is closed using the close function.
Syntax: close(FileHandle);
Parameters:
 FileHandle- The FileHandle to be closed.
Reading from and Writing to a File using FileHandle
Reading from a FileHandle can be done through the print function.
Syntax: print(<FileHandle>);
Parameters:
 FileHandle- FileHandle opened in read mode or a similar mode.
Writing to a File can also be done through the print function.
Syntax: print FileHandle String
Parameters:
 FileHandle- FileHandle opened in write mode or a similar mode.
 String- The String to be inserted in the file.
Different Modes in File Handling

Mode Explanation

“<“ Read Only Mode

“>” Creates file (if necessary), Clears the contents of the File and Writes to it

“>>” Creates file (if necessary), Appends to the File

“+<“ Reads and Writes but does NOT Create

“+>” Creates file (if necessary), Clears, Reads and Writes

“+>>” Creates file (if necessary), Reads and Appends

30
Examples: Consider a file Hello.txt containing the string “Welcome to GeeksForGeeks!!!”
initially.
1. Mode = “<“ This is read-only Mode. This mode is used to Read the content line by line from
the file.
 Perl

#!/usr/bin/perl

# Opening a File in Read-only mode


open(r, "<", "Hello.txt");

# Printing content of the File


print(<r>);

# Closing the File


close(r);

Output:

Mode = “>” This is write-only Mode. Original contents of the File are cleared once it is opened
in this Mode. It creates a new File with the same name, if one is not found.
 Perl

#!/usr/bin/perl

# Opening File Hello.txt in Read mode


open(r, "<", "Hello.txt");

# Printing the existing content of the file


print("Existing Content of Hello.txt: " . <r>);

31
# Opening File in Write mode
open(w, ">", "Hello.txt");

# Set r to the beginning of Hello.txt


seek r, 0, 0;

print "\nWriting to File...";

# Writing to Hello.txt using print


print w "Content of this file is changed";

# Closing the FileHandle


close(w);

# Set r to the beginning of Hello.txt


seek r, 0, 0;

# Print the current contents of Hello.txt


print("\nUpdated Content of Hello.txt: ".<r>);

# Close the FileHandle


close(r);

1. Output:

2. Mode=”>>” This is Append Mode. Original content of the File is not cleared when it is
opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at
the End. It creates a new File with the same name, if one is not found.
 Perl
32
#!/usr/bin/perl

# Opening File Hello.txt in Read mode


open(r, "<", "Hello.txt");

# Printing the existing content of the file


print("Existing Content of Hello.txt: " . <r>);

# Opening the File in Append mode


open(A, ">>", "Hello.txt");

# Set r to the beginning of Hello.txt


seek r, 0, 0;

print "\nAppending to File...";

# Appending to Hello.txt using print


print A " Hello Geeks!!!";

# close the FileHandle


close(A);

# Set r to the beginning of Hello.txt


seek r, 0, 0;

# Print the current contents of Hello.txt


print("\nUpdated Content of Hello.txt: ".<r>);

# Close the FileHandle


close(r);

Output:
33
1. Mode = “+<“ This is Read-Write Mode. This can be used to overwrite an existing String in
File. It cannot create a new File.
 Perl

#!/usr/bin/perl

# Open Hello.txt in Read-Write Mode


open(rw, "+<", "Hello.txt");

# Print original contents of the File.


# rw is set to the end.
print("Existing Content of Hello.txt: ".<rw>);

# The string is attached at the end


# of the original contents of the file.
print rw "Added using Read-Write Mode.";

# Set rw to the beginning of the File for reading.


seek rw, 0, 0;

# Printing the Updated content of the File


print("\nUpdated contents of Hello.txt: ".<rw>);

# Close the FileHandle


close(rw);

Output:

34
Mode = “+>” This is Read-Write Mode. The difference between “+<” and “+>” is that “+>” can
create a new File, if one with the name is not found, but a “+<” cannot.
 Perl

#!/usr/bin/perl

# Opening File Hello.txt in Read mode


open(r, "<", "Hello.txt");

# Printing the existing content of the file


print("Existing Content of Hello.txt: " . <r>);

# Closing the File


close(r);

# Open Hello.txt in Read-Write Mode


open(rw, "+>", "Hello.txt");

# Original contents of the File


# are cleared when the File is opened
print("\nContents of Hello.txt gets cleared...");

# The string is written to the File


print rw "Hello!!! This is updated file.";

# Set rw to the beginning of the File for reading.


seek rw, 0, 0;

35
print("\nUpdated Content of Hello.txt: " .<rw>);

# Closing the File


close(rw);

Output:

Mode = “+>>” This is Read-Append Mode. This can be used to Read from a File as well as
Append to it. A new File with same name is created, if one is not Found.
 Perl

# Open Hello.txt in Read-Append Mode


open(ra, "+>>", "Hello.txt");

# Set ra to the beginning of the File for reading.


seek ra, 0, 0;

# Original content of the File


# is NOT cleared when the File is opened
print("Existing Content of the File: " . <ra>);

print "\nAppending to the File....";

# The string is appended to the File


print ra "Added using Read-Append Mode";

# Set ra to the beginning of the File for reading.


seek ra, 0, 0;

36
# Printing the updated content
print("\nUpdated content of the File: " . <ra>);

# Closing the File


close(rw);

Output:

 Open a FileHandle to write i.e. “>”, “>>”, “+<“, “+>” or “+>>”.


 Select the FileHandle using select function.
2-Mark Questions (Short Answers)
1. What are the different modes available for opening a file in Perl?
2. How do you open a file in Perl? Write the basic syntax.
3. What is the difference between die and warn in Perl file handling?
4. What does the <FH> operator do in Perl?
5. How do you close a file in Perl? Provide an example.
6. What is the purpose of the binmode function in file handling?
7. What happens if you try to open a non-existent file in read mode?
8. What is the default file handle in Perl?
9. What is the difference between print and write in Perl?
10. How do you check if a file exists before opening it?

5-Mark Questions (Brief Explanations)


1. Explain the different file modes in Perl (>, >>, <, +>).
2. Write a Perl script to open a file, read its content, and display it.
3. What are tell() and seek() functions in Perl? Explain with examples.
4. How do you read a file line by line using a while loop in Perl?
5. Describe the difference between sysopen and open in Perl.
6. Write a Perl script to check whether a file is readable, writable, and executable.

37
7. Explain how to write to a file in Perl and provide a code example.
8. What is the use of the unlink function in Perl? How do you delete a file?
9. Discuss the role of error handling (or die) in Perl file operations.
10. Write a script to count the number of lines, words, and characters in a file.

10-Mark Questions (Detailed Explanations and Coding)


1. Write a Perl script to read from a file and write its content into another file.
2. Explain different methods of reading a file in Perl (line-by-line, entire file, character-by-
character).
3. Write a Perl program that appends text to an existing file and displays the updated content.
4. Discuss the use of flock() for file locking in Perl. Provide an example script.
5. Explain the truncate() function in Perl with a practical example.
6. Write a script that reads a CSV file, processes its data, and writes the output to a new file.
7. Discuss error handling techniques in file handling with appropriate examples.
8. Write a Perl script to search for a specific word in a file and replace it with another word.
9. Explain the select() function in file handling and demonstrate its use.
10. Write a Perl script to create a log file that stores user input with timestamps.

38

You might also like