CSC205 PDF
CSC205 PDF
CSC205
STRUCTURED PROGRAMMING
https://odlearning.futa.edu.ng
Open and Distance Learning Centre, The Federal University of Technology Akure
P.M.B. 704, Akure, Ondo State, Nigeria
FEDERAL UNIVERSITY OF TECHNOLOGY, AKURE
ONDO STATE, NIGERIA
i|Page
Course Development Team
Instructional Designer
ODLC Mr. J. B. Oluwagbemi
ODLC Mr. P. K. Olotu
Language Editor
ODLC Dr. (Mrs.) F. Oguntade
E-Tutor
Department Name
Computer
ODLC Expert
Unit Name
INTEDH Dr. A. I. Makinde
Course Coordinator
Department Name
Computer Prof. S. A. Oluwadare
Programme Coordinator
Dr. E. O. Ibam
Centre Director
Prof. F. I. Alao
ii | P a g e
CSC 205 - Study Guide
Introduction
CSC 205: Structured Programming is a 2-credit unit course for students studying towards
acquiring a Bachelor of Science in Computer Science and other related disciplines.
The course is divided into 8 study sessions and 20 study units. It provides an overview of
programming languages and their types; and explains the principles of abstraction and
modularity. The elements of structured programming are then given before outlining the
steps in program design and execution. An introduction to the PERL programming language
follows with how to use and apply operators and control statements. Functions and arrays in
PERL are then discussed, finally ending the course with a study of structures and pointers in
PERL programming language.
Course Aim
This course is designed for a semester in Structure Programming Language using
PERL for undergraduate Computer Science. The course covers general concepts
Structure Programming Language. The course covers the basic features needed to be
good Computing field and how to write Structure Programming language in PERL.
Course Objectives
It is important to note that each unit has specific objectives. Students should study
them carefully before proceeding to subsequent units. Therefore, it may be useful to
refer to these objectives in the course of your study of the unit to assess your progress.
You should always look at the unit objectives after completing a unit. In this way, you
can be sure that you have done what is required of you by the end of the unit.
However, below are overall objectives of this course. On completing this course, you
should be able to:
Define programs and classify programming languages
State the advantages and disadvantages of high and low–level languages
iii | P a g e
State the characteristics of a good program
List the various phases of program development.
Explain the steps involved in problem definition and analysis
Describe functions and Procedures in program
Illustrate a typical function structure for sorting numerical arrays in PERL
language.
Define a class in Object–oriented programming
Explain the abstraction costs and benefits
Define modularity in programming.
State the advantages of modular programming approach
Describe the real-life application of modularity concept.
Explain the importance of header file, module implementation and main
program in PERL programming language.
Illustrate the structure of interface file in PERL language declarations.
State the purpose of IMPORT and the EXTERN macros in PERL language
program declaration
State the advantages and disadvantages of structure programming
Describe the examples of programming paradigms.
State the various programming paradigms
Describe each of the named programming paradigms and programming
languages associated with it.
Give a brief history of PERL Programming Language.
Explain the taxonomy of PERL programming types
Explain the importance of studying PERL programming language.
Describe the characteristics and uses of PERL Program.
Illustrate the structure of a PERL Programming language.
Explain the contents of the PERL program structure.
Explain the processes involved in compilation and execution of PERL
program.
iv | P a g e
Describe the sample input/ output steps used in program compilation and
execution.
List the character set in PERL
Apply the character set in constructing variables and identifiers
Differentiate between a variable and a keyword
Explain what a data type is
Define a constant
State the rules for constructing integer constants
State the rules for constructing real constants
State the rules for constructing real constants expressed in exponential form
State the rules for constructing character constants
Format your input
Format your output
Differentiate between the output of integer float
Differentiate between the input of integer float
Define an operator
Use operators in expressions
Mention the various operators applicable to PERL programming
Describe each of the operators
State the three control structures inherent in PERL
State the generic syntax for the various structures
Use these structures to write a program code or a block of code
Describe each of the structure
Manually simulate a program code involving the structures
Differentiate between monolithic Vs modular Programming
State the disadvantages of monolithic Programming
State the advantages of modular Programming
Declare a function
Outline the various function categories
Differentiate between a user define functions vs standard function.
v|Page
Differentiate between call by value and call by reference
Describe an array
Differentiate between one-dimensional and a two-dimensional array
Initialize one-dimensional, two-dimensional and multi-dimensional arrays
State the syntax of array declaration
Define a string
Differentiate between a string and a character
Manipulate string
Mention some commonly used string input/output library functions
Read and write string
Declare a string variable
Understand PERL structures and pointers
Know how to define and use structures and pointers in PERL
Course Materials
The major components of the course are:
1. Course Guide
2. Study Units
3. Text Books
4. Tutor Marked Assignments
5. Presentation Slides
6. Interactive DVD
7. Electronic Lecture Materials via Learning Management System (LMS)
8. Printed Lecture Materials
vi | P a g e
Study Units
There are 14 Study Units and 6 Study Sessions in this course. They are:
Study Session 1: Programing Languages
The following texts and Internet resources links will be of enormous benefits to you in
learning this course:
vii | P a g e
Structured Programming with C++ by Kjell Backman, 2012
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
www.academia.edu/25814963/An_Introduction_to_Computer_Science
Assignment File
The assignment file will be given to you in due course. In this file, you will find all the details
of the work you must submit to your tutor for marking. The marks you obtain for these
assignments will count towards the final mark for the course. Altogether, there are tutor
marked assignments for this course.
Presentation Schedule
The presentation schedule included in this course guide provides you with important dates for
completion of each tutor marked assignment. You should therefore endeavour to meet the
deadlines.
Assessment
There are two aspects to the assessment of this course. First, there are tutor marked
assignments; and second, the written examination. Therefore, you are expected to take note of
the facts, information and problem solving gathered during the course. The tutor marked
assignments must be submitted to your tutor for formal assessment, in accordance to the
deadline given. The work submitted will count for 40% of your total course mark. At the end
of the course, you will need to sit for a final written examination. This examination will
account for 60% of your total score.
Assignment Marks
Assignment 1- 6 40% of the course marks
End of Course Assessment 60% of overall course marks
Total 100% of course materials
viii | P a g e
Assessment Questions, In-text Questions and tutor marked assignments that you have
previously encountered. Furthermore, all areas of the course will be examined. It would be
better to use the time between finishing the last unit and sitting for the examination to revise
the entire course. You might find it useful to review your TMAs and comment on them
before the examination. The final examination covers information from all parts of the
course. Most examinations will be conducted via Computer Based Testing (CBT).
The following are practical strategies for working through the course
1. Read the course guide thoroughly
2. Organize a study schedule. Refer to the course overview for more details. Note the
time you are expected to spend on each unit and how the assignment relates to the
units. Important details, e.g. details of your tutorials and the date of the first day of the
semester are available. You need to gather together all this information in one place
such as a diary, a wall chart calendar or an organizer. Whatever method you choose,
you should decide on and write in your own dates for working on each unit.
3. Once you have created your own study schedule, do everything you can to stick to it.
The major reason that students fail is that they get behind with their course works. If
you get into difficulties with your schedule, please let your tutor know before it is too
late for help.
4. Turn to Unit 1 and read the introduction and the objectives for the unit.
5. Assemble the study materials. Information about what you need for a unit is given in
the table of Contents at the beginning of each unit. You will almost always need
both the study unit you are working on and one of the materials recommended
for further readings, on your desk at the same time.
6. Work through the unit, the Contents of the unit itself has been arranged to provide a
sequence for you to follow. As you work through the unit, you will be encouraged to
read from your set books
7. Keep in mind that you will learn a lot by doing all your assignments carefully. They
have been designed to help you meet the objectives of the course and will help you
pass the examination.
8. Review the objectives of each study unit to confirm that you have achieved them. If
you are not certain about any of the objectives, review the study material and consult
your tutor.
9. When you are confident that you have achieved a unit’s objectives, you can start on
the next unit. Proceed unit by unit through the course and try to pace your study so
that you can keep yourself on schedule.
10. When you have submitted an assignment to your tutor for marking, do not wait for its
return before starting on the next unit. Keep to your schedule. When the assignment is
returned, pay particular attention to your tutor’s comments, both on the tutor marked
ix | P a g e
assignment form and also written on the assignment. Consult you tutor as soon as
possible if you have any questions or problems.
11. After completing the last unit, review the course and prepare yourself for the final
examination. Check that you have achieved the unit objectives (listed at the beginning
of each unit) and the course objectives (listed in this course guide).
x|Page
Table of Contents
xi | P a g e
Study Session 1
1
Study Session 1: Programing Languages
Introduction
A program is a finite set of sequenced instructions or commands given to a computer in order
to carry out a particular task. To write a program for the computer to carry out these
instructions, there must be a means of communication. Humans communicate via natural
languages such as English, French, Chinese etc. Likewise, to communicate with the
computer, we also use languages known as programming languages. Programming is the
art of program writing using a particular programming language. It can also be said to be the
process of writing a set of instructions in sequential manner using programming language to
control the activity of a computer system.
2
Unit 1.1
Computer Programming
A computer programming language is an artificial language which is used in writing a set of
formal instructions to control the activities of a computer system. There are two main types
of computer programming languages; these are: Low-level language and High-level
language. Low-level languages also known as machine language, are machine dependent
and makes fast and efficient use of the computer. It requires no translator to translate the
code. It is directly understood by the computer. On the contrary, writing a program in high-
level language does not require knowledge of the computer in which the program is run.
Hence, high-level languages are machine independent, and which programs are portable to
other computers, and very easy to learn and write.
Machine Language: This is the only language computer understands. It is the native
language of the computer. The computer directly executes a program written in machine
language. These programs are coded using strings of 0’s and 1’s. It doesn’t need a translator.
• Very bulky
• They require much time for writing and reading.
3
• They are prone to error which is difficult to detect and correct.
• Very difficult to learn.
• Can only run on the computer it is designed (i.e., it is machine dependent)
4
other words, a high-level language is a convenient and simple means of describing the
information structures and sequences of actions required to perform a particular task.
5
Unit 1.2
The principles of data processing set the pace for obtaining the requirements of a good
program. In data processing, three phases are critical: The input, processing and the output
phases. Input constitutes what instruction and data goes into the system. Processing has to do
with what logic or tools are required to manipulate the data. Hence, we expect certain
characteristics from a good program or tool intended to process the data to yield informed
output.
There are various phases in the development of computer programs. These phases must be
strictly adhered to, to ensure a reliable, efficient program devoid of syntax and semantic
errors.
Example 1: Supposed you are asked to develop an application, what are the steps-by-step
procedure in writing a good programming?
Solution:
1.2.1 Characteristics of Good Programming
• Portability/Transferability: Must be able to work on any computer machine.
• Reliability: It can be relied upon to do what it is expected to do.
• Efficiency/cost saving: It must not cost more than its benefits and enables problem to
be solved appropriately, quickly and efficiently.
• Clarity and Simplicity: It should be as simple as possible to understand.
• Understandability/Readability: It must be readable and understandable by other
programmers and end users.
• Flexibility/Adaptability/Maintainability: A good program must be flexible adaptable
and maintainable in order to suit user’s need. Modification must be possible and very
easy.
6
1.2.2 Phases of Program Development (Programming)
The process of producing a computer program (software) may be divided into eight phases or
stages:
Problem definition/Analysis
Selection or development of an algorithm
Designing the program
Coding the programming statements
Compiling/Compilation stage
Testing/Running and Debugging the program
Documentation.
Maintenance
In data processing, three phases are critical: The input, processing and the output phases.
(i) Problem Definition/Analysis Stage: There is need to understand the problem that
requires a solution. The need to determine the data to be processed, form or type of
the data, volume of the data, what to be done to the data to produce the
expected/required output.
(ii) Selection or development of an algorithm: An algorithm is the set of steps required
to solve a problem written down in English language.
(iii) Designing the program: In order to minimize the amount of time to be spent in
developing the software, the programmer makes use of flowchart. Flowchart is the
pictorial representation of the algorithm developed in step 2 above. Pseudocode IPO
chart (input processing output) and HIPO (Hierarchical Input Processing and
Output) chart may be used in place of flowchart or to supplement flowchart.
(iv) Coding the statement: This involves writing the program statements. The
programmer uses the program flow chart as a guide for coding the steps the
computer will follow.
7
(v) Compiling: There is need to translate the program from the source code to the
machine or object code if it is not written in machine language. A computer
program is fed into the computer first, then as the source program is entered, a
translated equivalent (object program) is created and stored in the memory.
(vi) Running, Testing and Debugging: When the computer is activated to run a program,
it may find it difficult to run it because errors (syntax, semantics or logic, or
runtime) might have been committed. Manuals are used to debug the errors. A
program that is error free is tested using some test data. If the program works as
intended, real life data are then loaded.
(vii) Documentation: This is the last stage in software development. This involves
keeping written records that describe the program, explain its purposes, define the
amount, types and sources of input data required to run it. List the Departments and
people who use its output and trace the logic the program follows.
(viii) Maintenance: All the activities that occur after the completion of the program come
under the program maintenance. Program maintenance includes the following:
Finding and correcting the errors; Modifying the program to enhance it – i.e.,
adapting to some new concepts or when there is a change in the hardware or
operating system; Update the documentation; Add new features and functions;
Remove useless or redundant parts of code.
8
Summary of Study Session 1
A computer program is a set of instruction given to a computer to carry out a particular task.
Computer programs are written using programming languages. These languages can be
classified into low-level (i.e., machine and assembly languages) and high-level languages.
Machine language uses 0s and 1s while assembly uses mnemonics. The high level languages
use mathematical symbols in combination with English like words. Both the low-level and
high-level programming languages have their advantages and disadvantages. These are
stated in the main contents of the unit.
The characteristics of a good program are outlined which include: transferability, reliability,
efficiency, cost saving, simplicity, understandability, readability, flexibility, adaptability,
maintainability.
Problem definition/Analysis
Selection or development of an algorithm
Designing the program
Coding the programming statements
Compiling/Compilation stage
Testing/Running and Debugging the program
Documentation.
Maintenance
9
GLOSSARY OF TERMS
A high-level language (HLL): HLL is a programming language such as PERL, or
FORTRAN that enables a programmer to write programs that are more or less independent of
a particular type of computer. Such languages are considered high-level because they are
closer to human languages and further from machine languages.
Computer Programming: A computer programming language is an artificial language
which is used in writing a set of formal instructions to control the activities of a computer
system.
Machine Language: This is the only language computer understands. It is the native
language of the computer. The computer directly executes a program written in machine
language.
Low level language: This type of language is closer to the machine compared with the
human or natural language. The two major examples are the Machine language and the
Assembly language.
10
Pilot Answers
Pilot Answer 1.1
There are two major types of computer programming languages: the low-level language and high-
level language.
Low level language: This type of language is closer to the machine compared with the human or
natural language
11
Self-Assessment Questions (SAQs) for Study Session 1
This unit introduced the students to the basic knowledge of computer programming. It
defined computer program and discussed the two major classifications of programming
languages (the low- and high-level programming languages).
You can now assess how well you have achieved the learning outcomes for this study
session by answering the following questions. You can check your answers with the Notes
on the Self-Assessment questions at the end of this session.
12
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
13
Study Session 2
14
Study Session 2: Abstraction and Modularity
Introduction
As programmers began to write instructions that were equivalent to a few bytes, the level of
thinking in terms of what the computer was doing on a functional level raised the level of
abstraction. Statements and structured code can be thought of as assembly language
operations, at a higher level of abstraction. Statements are collected to form functions,
procedures, subroutines, or methods. The abstraction or grouping code and its data structures
is called object-oriented programming. However, the clump of code and data definitions is
called a class in most programming languages. In many software maintenance projects, the
cost of the additional performance of low levels of abstraction is far higher than the cost of
the computer cycles that would be required to run the program.
A module is basically a set of interrelated files that shares their implementation details but
hide it from the outside world. The main advantages of modular programming approach,
includes ease of use, reusability, and ease of maintenance. Modularity is applicable in real
life such as electrical devices that can plug into any outlet/socket. Modularization is a method
to organize large programs in smaller parts, i.e., the modules. Every module has a well-
defined interface toward client modules that specifies how “services” provided by this
module are made available. Moreover, every module has an implementation part that hides
the code, and any other private implementation details the clients’ module.
15
Unit 2.1
2.1.1 Abstraction
The history of programming has experienced rising levels of granularity. Decades ago,
programmers manipulated individual bits of codes. Then the assembly language was
invented, and programmers began to write instructions that were equivalent to a few bytes.
The advantage was clear: Instead of thinking in terms of essentially meaningless 1s and 0s,
you could think in terms of what the computer was doing on a functional level—move this
value to that memory location, multiply these two bytes together.
This is called raising the level of abstraction. Every time you raise the level of abstraction in
a programming language, you get more clearer, structured program (as measured in terms of
bits) for less work. The language at which you communicate with the computer can also be
altered into something closer to the way we communicate in English.
Each unit of the level of abstraction has a contract or agreement: The language makes an
exact promise of what the computer will do when the unit is executed. For the following
assembly language instruction:
LD (BC), A the language promises that it will move the value from the register named A into
the place in memory pointed to by registers B and C. Obviously, this is only a very small
piece of what you want the computer to do, such as word processing, video processing, etc.
but it’s a lot clearer and easier to use than its binary equivalent: 00000010
It may not seem any shorter or easier to remember LD (BC), A; but each of the letters here
has an explicit and easily remembered meaning: LD is short for LOAD; A, B, and C refer to
some registers, and (BC) refers to a way to do indirection into memory. 00000010 may be
just seven 0s and a 1, but the order is both critical and hard to memorize. Swapping two of
the bits to 00000100 means INC B (increment the B register), which is totally different.
Abstraction is one of the four cornerstones of Computer Science. It involves filtering out –
essentially, ignoring - the characteristics that we don't need in order to concentrate on those
that we do
16
2.1.2 Functions and Procedures
Statements and structured code can be thought of as assembly language operations, at a
higher level of abstraction. The next level of abstraction is to group statements into
operational units with contracts of their own. Statements are collected to form functions,
procedures, subroutines, or methods, as they are called in various languages. The beauty
about functions is that they limit even further the amount of code required to understand a
piece of code.
2.1.3 Classes
Structured programming and functions neatly solve some of the problems of maintenance by
limiting the amount of code you must look at in order to understand any given line. There’s
still one way that far off pieces of code can affect a particular line of code. The sort example
given earlier sorts only integers, which is not a particularly interesting job.
Even before object-oriented programming, there were ways to group chunks of data into
functional units. In C, these units are called structs. However, structs don’t have any reliable
way to compare them. You need some level of abstraction a little higher than provided by
structs that allows you to tell which of two structs should come first. The abstraction of
grouping code and its data structures is called objectoriented programming. The clump of
code and data definitions is called a class in most programming languages.
A function is simply a “chunk” of code that you can use over and over again, rather than
writing it out multiple times. Functions enable programmers to break down or decompose a
problem into smaller chunks, each of which performs a particular task.
17
Box 2.3: Subroutines
Subroutines are small blocks of code in a modular program designed to perform a particular
task. Since a subroutine is in itself a small program, it can contain any of the sequence ,
selection and iteration constructs.
Higher levels of abstraction lead to improved maintenance, simply because there’s less code.
The less code, the less you have to read to understand it. Certainly, there are limits to this, as
50 lines of clear code is preferable to 10 lines of total obscurity. In general, however, by
using higher levels of abstraction, improved maintainability is gained.
18
Unit 2.2
2.2.1 Modularity
Modular programming is the process of subdividing a computer program into separate sub-
programs. A module is a separate software component. It can be used in a variety of
applications and functions with other components of the system.
Some programs may have thousands or millions of lines and to manage. For such programs
such programs it becomes quite difficult as there might be too many of syntax errors or
logical errors present in the program, so to manage such programs, the concept of modular
programming is essential. The modular programming concept permits that each sub-
module contains something necessary to execute only one aspect of the desired functionality.
Modular programming therefore places emphasis on breaking of large programs into small
problems to increase the maintainability, readability of the code and to make the program
handy for any changes in future.
Modular programming is the process of subdividing a computer program into separate sub-
programs
Reusability: It allows the user to reuse the functionality with a different interface without
typing the whole program again.
Ease of Maintenance: It helps in less collision at the time of working on modules, helping a
team to work with proper collaboration while working on a large application.
19
Below is an example of a Real-life Example of Modules
Let’s consider a familiar modular system. Consider the electrical devices (microwaves,
electric kettles, washers, dryers, etc.) that can plug into any outlet/socket. None of these
device care if they are plugged into the electrical outlet in your house or your neighbor’s
house or your office, etc. They are designed to do their specific task and functionality when
they are plugged in and when the power is on, regardless the place they are in.
Application modules should follow the same philosophy. Regardless of the application and
even regardless of what application they plugged into, they should do their specific task and
only their specific task.
Also, in exactly the same way that an electrical device can easily be unplugged from the wall
outlet, a code module should be designed in such a way that it can easily be decoupled and
removed from your application.
Furthermore, as the removal of one electrical device has no impact on the functionality of
other devices that are plugged into your electrical system, the removal of a code module or a
series of code modules from your application should not have any effect on the functionality
of the other parts of your application.
This decoupling should also have no effect on the application, other than perhaps just losing
the specific functionality that was provided by that particular module or group of modules in
the application.
20
Subroutines
Subroutines divide a large programming job into more manageable pieces. Modern
programming languages all provide subroutines, which are also called functions, or macros
in other programming languages.
A subroutine lets you write a piece of code that performs some part of a desired computation
(e.g., determining the length of DNA sequence). This code is written once and then can be
called frequently throughout the main program. Using subroutines speeds the time it takes to
write the main program, makes it more reliable by avoiding duplicated sections (which can
get out of sync and make the program longer), and makes the entire program easier to test. A
useful subroutine can be used by other programs as well, saving you development time in
the future. As long as the inputs and outputs to the subroutine remain the same, its internal
workings can be altered and improved without worrying about how the changes will affect
the rest of the program. This is known as encapsulation.
The benefits of subroutines that I've just outlined also apply to other approaches in software
engineering. PERL modules are a technique within a larger umbrella of techniques known as
software encapsulation and reuse. Software encapsulation and reuse are fundamental to
object-oriented programming.
Perl is a family of script programming languages that is similar in syntax to the C language. It
is an older, open source, general use, interpreted language. Perl was developed with usability
in mind. Its efficient design lets developers do a lot with a little bit of code.
A related design principle is abstraction, which involves writing code that is usable in many
different situations. Let's say you write a subroutine that adds the fragment TTTTT to the end
of a string of DNA. If you then want to add the fragment AAAAA to the end of a string of
DNA, you have to write another subroutine. To avoid writing two subroutines, you can write
one that's more abstract and adds to the end of a string of DNA whatever fragment you give it
as an argument. Using the principle of abstraction, you've saved yourself half the work.
Here is an example of a PERL subroutine that takes two strings of DNA as inputs and
returns the second one appended to the end of the first:
21
sub DNAappend {
my ($dna, $tail) = @_;
return($dna . $tail);
}
This subroutine can be used as follows:
my $dna = 'ACCGGAGTTGACTCTCCGAATA';
my $polyT = 'TTTTTTTT';
In my projects, I gather subroutine definitions into separate files called libraries, or modules,
which let me collect subroutine definitions for use in other programs. Then, instead of
copying the subroutine definitions into the new program (and introducing the potential for
inaccurate copies or for alternate versions proliferating), I can just insert the name of the
library or module into a program, and all the subroutines are available in their original
unaltered form. This is an example of software reuse in action.
22
Namespaces
A namespace is implemented as a table containing the names of the variables and subroutines
in a program. The table itself is called a symbol table and is used by the running program to
keep track of variable values and subroutine definitions as the program evolves. A namespace
and a symbol table are essentially the same thing. A namespace exists under the hood for
many programs, especially those in which only one default namespace is used.
Large programs often accidentally use the same variable name for different variables in
different parts of the program. These identically named variables may unintentionally interact
with each other and cause serious, hard-to-find errors. This situation is called namespace
collision. Separate namespaces are one way to avoid namespace collision.
The package declaration described in the next section is one way to assign separate
namespaces to different parts of your code. It gives strong protection against accidentally
using a variable name that's used in another part of the program and having the two
identically-named variables interact in unwanted ways.
23
Summary of Study Session 2
In this unit you have learnt the concept of modularity and the advantages derivable thereof.
A real-life example was illustrated considering electrical devices microwaves, electric
kettles, washers, dryers, etc. You also leant how to implement modular programming in
PERL programming language.
Abstraction is having a global view of the programming task at hand. It hides details of the
task. Abstraction has it costs and benefits. Functions and procedures are ways of splitting a
complex task into smaller units or modules. This makes room for easy design and
implementation a program.
24
GLOSSARY OF TERMS
Function: A function is simply a “chunk” of code that you can use over and over again,
rather than writing it out multiple times. Functions enable programmers to break down or
decompose a problem into smaller chunks, each of which performs a particular task.
Abstraction is a programming principle that allows for the hiding of details of the task at
hand. Emphasis is on functionalities. In object oriented programming abstraction is
achieved via the combination of code and data into one container. The definition of both the
code and data together is a class. Class is a blue print for the production of objects.
25
Pilot Answers
Pilot Answer 2.1
Ease of Use: This approach allows simplicity, as lines of program code can be
accessed in the form of modules, rather than focusing on the entire thousands and
millions of lines code. This allows ease in debugging the code and prone to less error.
Reusability: It allows the user to reuse the functionality with a different interface
without typing the whole program again.
Ease of Maintenance: It helps in less collision at the time of working on modules,
helping a team to work with proper collaboration while working on a large
application.
return $largest;
}
# Example usage
my $result = find_largest(10, 5, 8);
print "The largest number is: $result\n";
26
Self-Assessment Questions (SAQs) for Study Session 2
i. State the benefits of modularization on large and complex programs
ii. What is Abstraction?
iii. Write a function to select the largest of 3 numbers
27
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
28
Study Session 3
Content
Introduction
Learning Outcomes for Study Session 3
Learning Activities
Unit 3.1: Overview of Structured Programming
3.1.1 Structured Programming Concept
3.1.2 Advantages of Structured Programming
3.1.3 Disadvantages of Structured Programming
Unit 3.2: Programming Language Paradigms
3.2.1 Imperative Paradigm
3.2.2 Functional Paradigm
3.2.3 Logical Paradigm
3.2.4 Object Oriented Paradigm
3.2.5 Other Paradigms
Summary for Study Session 3
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 3
References/Further Reading
29
Study Session 3: Elements of Structured Programming
Introduction
In structured programming design, programs are broken into different functions. These
functions are also known as modules, subprograms, subroutines or procedures. Structured
programming minimizes the chances of the function affecting another. It allows for clearer
programs code. It made global variables to disappear and replaced by the local variables.
30
Unit 3.1
Structured programming minimizes the chances of the function affecting another. It allows
for clearer programs code. It made global variables to disappear and replaced by the local
variables. Due to this change one can save the memory allocation space occupied by the
global variable. Its organization helps in the easy understanding of programming logic. So
that one can easily understand the logic behind the programs. It also helps the newcomers of
any industrial technology company to understand the programs created by their senior
workers of the industry.
31
• Java
• C#
• Pascal
•
3.1.2 Advantages of Structured programming
• It is user friendly and easy to understand.
• Similar to English vocabulary of words and symbols.
• It is easier to learn.
• They require less time to write.
• They are easier to maintain.
• These are mainly problem oriented rather than machine based.
• Program written in a higher-level language can be translated into many machine
languages and therefore can run on any computer for which there exists an
appropriate translator.
• It is independent of machine on which it is used, i.e., programs developed in high
level languages can be run on any computer.
32
changes in data types done by the programmer in data type handled. Otherwise, it
requires rewriting several functions.
Box 3.2: Object
An object within Perl is merely a reference to a data type that knows what class it belongs to.
The object is stored as a reference in a scalar variable. Because a scalar only contains a
reference to the object, the same scalar can hold different objects in different classes.
Unit 3.2
33
Box 3.3: Loop
Encapsulation describes bundling data and methods that work on that data within one unit,
34
like a class in Java. We often use this concept to hide an object’s internal representation or
state from the outside. This is called information hiding.
35
Summary for Study Session 3
In this session you have learnt some programming paradigms. These include Imperative,
Functional, Logical, Object-Oriented Paradigms etc. These Paradigms are briefly discussed.
The programming languages associated with these Paradigms are also discussed.
You also have learnt structured programming concept, Advantages and Disadvantages of
Structured programming. Some programming languages that support Structured
programming approach are also listed.
36
GLOSSARY OF TERMS
Programming Paradigm: A programming paradigm, or programming model, is an
approach to programming a computer based on a mathematical theory or a coherent set of
principles.
37
Pilot Answers
Pilot Answer 3.1
Structured programming is a programming paradigm that emphasizes the use of structured
control flow constructs, such as loops, conditionals, and subroutines, to organize and manage
the execution of a program. This approach to programming can lead to improved
programming efficiency in several ways:
Readability and Maintainability: Structured programming promotes the use of clear
and organized code structures, making programs easier to read, understand, and
modify.
Modular Design: Structured programming encourages the decomposition of a
program into smaller, self-contained modules.
Control Flow Clarity: Structured programming provides clear control flow constructs
like loops and conditionals that allow for straightforward expression of program logic.
Debugging and Error Handling: The structured nature of the code in structured
programming aids in the identification and resolution of bugs and errors.
Reusability and Scalability: Structured programming promotes code reusability and
scalability.
Code Optimization: Structured programming techniques make it easier to analyze and
optimize code performance.
38
Self-Assessment Question (SA Qs) for Study Session 3
1. Differentiate with examples, the difference between functional and object-oriented
programming paradigms.
2. Describe how structured programming can lead to programming efficiency.
39
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
40
Study Session 4
Content
Introduction
Learning Outcomes for Study Session 4
Learning Activities
Unit 4.1 Overview of PERL and PERL Program Design
4.1.1 PERL basics
4.1.2 Executing a PERL program (script)PERL Variables and Data Types
4.1.3 Naming Convention
4.1.4 Basic Operators
4.1.5 PERL Program Design
4.1.6 Hashes
4.1.7 I/O BASICS
Unit 4.2 Executing a PERL Program
4.2.1 PERL Unless
4.2.2 Pearl Loop
Summary for Study Session 4
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 4
References/Further Reading
41
Study Session 4: Structured Programming with PERL
PERL stands for “Practical Extraction and Reporting Language”. It is an interpreted
programming language. An interpreter runs through a program line by line and executes each
command. The code itself is platform independent. It is a scripting language i.e. it contain
series of commands that are interpreted one by one at runtime and it is used to give
instruction to other software such as web browser, server or standalone. It is best known for
text processing – dealing with files, strings and regular expression (good for string
processing). PERL are useful the following.
i. Tool for general system administration
ii. Processing textual or numerical data
iii. Database interconnectivity
iv. Common Gateway Interface (CGI/Web) programming
v. Driving other programs (FTP, Mail, WWW, OLE)
Control Structures can be considered as the building blocks of computer programs. They are
commands that enable a program to “take decisions”, following one path or another. A
program is usually not limited to a linear sequence of instructions since during its process it
may bifurcate, repeat code or bypass sections.
42
Unit 4.1
{ statement_1
statement_2 …
statement_n
}
print "Hello.";
{ statement }
4. Comment lines are preceded with # symbol. The # can come at any point in the line:
Create a plain-text document with the following program code in a text editor:
43
#!/usr/bin/PERL print 'Hello,
World!';
Save the document as "myprogram.pl" and run it from the prompt as follows:
Array is a variable that holds multiple values in series. Array names begin with @:
A hash is a variable that holds pairs of data. Hash names begin with %:
"brown");
Variable names begin with the special type-indicating character ($, @, or %, respectively),
followed by any combination of letters, numbers, and underscores. The first character after
the $, etc. must be a letter or underscore, not a number. Note: Variable names are case-
sensitive. Some valid variable names are: $time_of_arrival, $Time_of_Arrival,
$timeofdeparture and $TOD.
A scalar is a single value that is not an array. A scalar may be string, integer, or a floating-
point. For example, "my $value="example";" is an example of a scalar in Perl, where $value
is equal to the string 'example'
44
Box 4.2: Hash
Hashing is the process of transforming any given key or a string of characters into another
value. This is usually represented by a shorter, fixed-length value or key that represents and
makes it easier to find or employ the original string.
3. Examples:
45
%SIG The hash used to set signal handlers for various signals
SCALARS
Scalars are simple variables that are either numbers or strings of characters. Scalar variable
names begin with a dollar sign followed by a letter, then possibly more letters, digits, or
underscores. Variable names are case-sensitive. Two type of scalar data types are:
1. Numbers
2. Strings
Numbers
2. floating point numbers i.e. real numbers, like 3.14, 0.333, 6.74
Strings
Strings are simply sequences of characters. There are two different types of strings:
Single quotation marks are used to enclose data you want to be taken literally. Example are:
#!/usr/bin/PERL
$num = 7;
$txt = ‘it is $num’; print $txt;
Output it is $num
Double quotation marks are used to enclose data that needs to be interpolated before
processing. That means that escaped characters and variables aren’t simply literally inserted
46
into later operations, but are evaluated on the spot. Escape characters can be used to insert
newlines, tabs etc.
$num = 7;
$txt = “it is $num”; print $txt;
Output: it is 7
Here due to double quotes values of $num is taken added to the value of $txt. Double-quotes
interpolate scalar and array variables, but not hashes. On the other hand, you can use double
quotes to interpolate slices of both arrays and hashes.
\n Newline
\r Carriage return
\t Tab
\b Backspace
\e Escape \\
Backslash
\” Double quote
\’ Single quote \l
lowercase next letter
47
String
Example Name Result
$a . “string” Concatenation String built from pieces
“$a string” Interpolation String incorporating the value of $a
$a x $b Repeat String in which $a is repeated $b times
Assignments Operator
So that $a += $b is equivalent to $a = $a + $b
$a -= $b $a = $a - $b
$a *= $b $a = $a * $b
$a /= $b $a = $a / $b
$a %= $b $a = $a % $b
This also works for the string concatenation operator: $a.= “\n”
The autoincrement and autodecrement operators are special cases of the assignment
operators, which add or subtract 1 from the value of a variable:
48
Logical Operators
Examples
49
@grades = ("98", "84", "73", "89"); print "$grades[0]
and $grades[2]"; @VOTs = ("400", "378", "352");
print @VOTs; 400378352 print "@VOTs"; 400 378
352
print '@VOTs'; # to review
@VOTs print "Name:\tBecky\nEyes:\thazel\n";
Name: Becky
Eyes: hazel $name =
"Alejna";
1. my
2. local
3. our
Use my to declare any variable which is specific within a block i.e. within the curly braces.
#!/bin/PERL my
$var=5;
if(i) {
my $var_2=$var;
} print $var_2;
The output of the program will be nothing. In the example, two variables are declared, one
inside if block ($var_2) and the other outside the if block ($var). The variable declared
outside the block will be accessible to if block but the variable which was declared inside if
block won’t be accessible to the outer program.
The local modifier mask the same variable values to different values without actuaclly
changing the original values of the variable, suppose we have a variable $a for which the
50
value is assigned 5, you can actually change the vale of that variable by re-declaring the same
variable using local keyword without altering the original value of the variable which is 5 as
follows:
#!/bin/PERL my
$var=5;
{
Local $var = 3;
Print “local, \$var = $var \n”;
}
print “global, \$var = $var \n”;
An array is a special type of variable which stores data in the form of a list; each element can
be accessed using the index number which will be unique for each and every element. You
can store numbers, strings, floating values, etc. in your array.
Defining Arrays
In PERL, you can define an array using ‘@’ character followed by the name that you want to
give.
Dynamic array
Dynamic arrays are those that you declare without specifying any value on them. We store
value in the array during runtime from string scalar variable using the split function. Two
51
ways it does this is split up on spaces or commas. . Example on split by spaces is given
below:
print "$#people";
2
You can sort the elements of an array or the keys of a hash with the function sort. Note: By
default, it sorts both strings and numbers alphabetically!
52
Sorting Array Keys
A very common type of loop makes use of the functions sort and keys. The latter yields all
the keys (not the values) in an array.
%signs = ("Frank" => "Capricorn", "Amanda" => "Scorpio"); foreach $person (sort
keys %signs) { print "$person: $signs{$person}\n";
}
Amanda: Scorpio
Frank: Capricorn
@b = reverse(@a);
There are two ways of adding new elements to existing arrays. If we know the index we want
the element to have, we can do this:
If we simply want to add an element to the end of an array, we can use push:
push(@numbers, "990");
210 450 333 990
Many list-processing functions operate on the paradigm in which the list is a stack. The
highest subscript end of the list is the “top,” and the lowest is the bottom.
4.1.6 Hashes
A hash (or associative array) is an unordered set of key/value pairs whose elements are
indexed by their keys. Hash variable names have the form %foo.
A hash can also hold as many scalars as the array can hold. The only difference is that instead
of index we have keys and values. A hash contains an unordered set of key/value pairs whose
elements are indexed by their keys. A has can be declared starting with % followed by the
name of the hash.
Hash Variables and Literals
Hash Functions
The keys’ function returns a list of all the current keys for the hash in question.
@hashkeys = keys(%hash);
In a scalar context, the keys’ function gives the number of elements in the hash. Conversely,
the values function returns a list of all current values of the argument hash:
@hashvals = values(%hash);
You can remove elements from a hash using the delete function:
delete $hash{‘key’};
54
4.1.8 I/O Basics
PERL needs data to interact with. Input refers to getting information into your program while
the output is the information obtained from a program.
Taking Inputs
The input from the keyboard (standard input) can be achieved as follows:
my $name declares a scalar variable. It can hold a number (integer or real), or an arbitrary
length string. <STDIN> means read one line from stdin. The line read is then assigned to
$name. The second print statement prints the result of the string "\nhello $name!\n" after
variable interpolation: the current value of $name is interpolated into the string in place of the
character sequence $name. For instance, if $name = "Kola" then the string would be "\nhello
Kola!\n". The < > operator reads a line and returns it including the newline (\n) at the end. To
get rid of these new line use chomp as follows:
Writing Output
The output is displayed using print function. The print function can take any number of
arguments and prints them to the standard output (usually the screen).
2. Write a program to create an Array , sort the array element and add values to the array.
55
Unit 4.2
The basic construction to execute blocks of statements is the if statement. The if statement
permits execution of the associated statement block if the test expression evaluates as true. It
is important to note that unlike many compiled languages, it is necessary to enclose the
statement block in curly braces, even if only one statement is to be executed.
if (expression_one) { true_one_statement;
} elsif (expression_two) { true_two_statement;
} else { all_false_statement;
}
Example 4.5
The “ternary” operator is another nifty one to keep in your bag of tricks:
my $a = 5;
unless ($a==5)
{
56
print “inside the unless block – The value is $a”;
}
else
{
print “Inside else block --- The value is $a”;
}
Output:
Loop statements are used to repeat the executing of some code. PERL supports four types of
control structures (similar to other programming languages) for, foreach, while and until.
PERL provides several different means of repetitively executing blocks of statements.
For loop
The code block will execute till the condition is satisfied. The for loop has three semicolon
separated expressions within its parentheses. These expressions function respectively for the
initialization, the condition, and incrementing as shown below:
Conditions are a key part of programming, but are also something that you probably use
every day without thinking about it. A condition is a statement that can be either true or false,
and programmers can use conditions to trigger actions.
Foreach
57
The foreach statement is much like the for statement except it loops over the elements of
a list:
my @array = (1..5); foreach (@array) { print “The value is $_\n";#This is same as the
above #code
}
Output
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
We can obtain hash keys and values using foreach as follows:
my %hash = (‘Tom’ => 23, ‘Jerry’ => 24, ‘Mickey’ => 25); foreach my $key (keys
%hash) { print “$key \n";
}
Output
Mickey
Tom
Jerry
58
While
The PERL while loop is a control structure, where the code block will be executed till the
condition is true. The code block will exit only if the condition is false. Example is as
follows:
#!/usr/bin/PERL $a=1;
while ($a<3) { print “$a\n”;
$a=$a+1;
}
Output
1
2
3
Do-while
Do while loop will execute at least once even if the condition in the while section is false.
Foe example:
#!/usr/bin/PERL $a=1; do {
print “$a\n”; $a=$a+1;
}
while ($a<=3)
print “Now value is greater than 3”;
Output
1
2
3
It is possible to exit the loop before the end of the loop via three methods: next, redo, and last
statements.
59
next means "skip over everything else in the block, increment the counter, and
evaluate the conditional again."
redo means "skip over everything else in the block and evaluate the conditional again,
without incrementing the counter."
last means "exit the block and never come back." Example:
60
Summary of Study Session 4
In this study session, you have learnt Selection (if Statement, else-if Statement, else), iterative
(while statement, do-while loop, for loop). You have also learnt that:
A variable can be considered as a container which holds one or more values. Once
defined, the variable remains, but the value or values can change over and over again.
Scalars are simple variables that are either numbers or strings of characters.
Scalar variable names begin with a dollar sign followed by a letter, then possibly
more letters, digits, or underscores. Variable names are case-sensitive.
An array is a special type of variable which stores data in the form of a list; each
element can be accessed using the index number which will be unique for each and
every element. You can store numbers, strings, floating values, etc. in your array.
A hash (or associative array) is an unordered set of key/value pairs whose elements
are indexed by their keys.
PERL needs data to interact with. Input refers to getting information into your
program while the output is the information obtained from a program.
The output is displayed using print function. The print function can take any number
of arguments and prints them to the standard output (usually the screen).
61
GLOSSARY OF TERMS
PERL: PERL programming language has control structures which make PERL qualify as a
structured programming language. These structures include sequence, selection and repetition
structure.
ARRAY: a number of mathematical elements arranged in rows and columns. (2) : a data
structure in which similar elements of data are arranged in a table
62
Pilot Answers
2.
# Create an empty array
array = []
63
add_value(value)
elif choice == '2':
sort_array()
elif choice == '3':
print("Array:", array)
elif choice == '4':
print("Exiting the program...")
break
else:
print("Invalid choice. Please try again.")
This program provides a menu-driven interface where you can choose to add a value to the
array, sort the array, print the array, or exit the program. The array is initially empty, and you
can add values to it using the add_value() function, which appends the provided value to the
array. The sort_array() function sorts the elements in the array using the built-in sort()
method. The sorted array can be printed using the "Print the array" option.
2.
# Function to calculate the grade based on the score
def calculate_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
64
return "D"
else:
return "F"
# Main program
score = float(input("Enter the student's score: "))
grade = calculate_grade(score)
In this program, the user is prompted to enter the student's score in the CSC 205 course. The
calculate_grade() function takes the score as an input and determines the corresponding grade
based on the following criteria:
65
Self-Assesment Question (SAQs) for Study Session 4
1. The foreach statement is much like the for statement except it loops over the
elements of a list:
66
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
67
Study Session 5
Content
Introduction
Learning Outcomes
Learning Activities
Unit 5.1: Subroutines and Functions
5.1.1 Invoking subroutines.
5.1.2 Passing arguments
5.1.3 Variable Scope
5.1.4 Regular Expressions
5.1.5 Character Classes
5.1.6 Special Variables
5.1.7 Regular Expression Operators
5.1.8 Split operator
5.1.9 Join operator
Unit 5.2: Pattern Matching
5.2.1 Grouping features
5.2.2 Anchoring Pattern
5.2.3 Alternation and bracketing patterns
5.2.4 RE special characters
5.2.5 Square bracket
5.2.6 File handles
5.2.7 Manipulating Files & Directories
Summary for Study Session5
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 5
References/Further Reading
68
Study Session 5: Introduction to PERL Programming Language
Introduction
PERL has the ability to make subroutines, which are user-defined functions. These lets you
recycle one chunk of code many times in one program. The name of a subroutine is another
PERL identifier (letters, digits, and underscores, but they can’t start with a digit) with a
sometimes-optional ampersand (&) in front
Regular expressions aren’t merely part of PERL; they’re also found in sed and awk, procmail,
grep, most programmers’ text editors such as vi and emacs, and even in more esoteric places.
If you’ve seen some of these already, you’re ahead of the game. Keep watching, and you’ll
see many more tools that use or support regular expressions, such as search engines on the
Web, email clients, and others.
69
Unit 5.1
PERL subroutines encapsulate blocks of code in the usual way. A subroutine can return a
scalar or an array. Subroutines are defined in PERL as:
sub subname { statement_1;
statement_2;
}
Subroutine definitions are global; there are no local subroutines.
To define your own subroutine, use the keyword sub, the name of the subroutine (without the
ampersand), then the block of code in curly braces which makes up the body of the
subroutine. Something like this:
sub marine
{ $n += 1;
# Global variable $n
print "Hello, sailor number $n!\n";
}
The ampersand (&) is the identifier used to call subroutines. They may also be called by
appended parentheses to the subroutine name:
name(); &name;
You may use the explicit return statement to return a value and leave the subroutine at any
point.
70
You invoke a subroutine from within an expression by using the subroutine name
(with the ampersand):‖
&marine; # says Hello, sailor number 1!
&marine; # says Hello, sailor number 2!
&marine; # says Hello, sailor number 3!
&marine; # says Hello, sailor number 4!
Most often, you refer to the invocation as simply calling the subroutine
Return Value
You always invoke a subroutine as part of an expression, even if you don’t use the
result of the expression. When you invoked &marine earlier, you were calculating the
value of the expression containing the invocation, but then throwing away the result.
Unless your subroutine is being particularly tricky and declares a “prototype,”
which dictates how a compiler will parse and interpret its invocation
arguments. This is rare—see the PERL sub documentation for more
information.
If you wish to be powerfully tricky, read the PERL documentation about
coderefs stored in private (lexical) variables.
A subroutine is a named block of code within a program that performs a specific task. It is
designed to be reusable and can be called multiple times from different parts of the program.
PERL passes the list to the subroutine; that is, PERL makes the list available for the
subroutine to use however it needs to
Arguments to a subroutine are passed as a single, flat list of scalars, and return values are
passed the same way. Any arguments passed to a subroutine come in as @_. To pass lists of
hashes, it is necessary to pass references to them:
71
@returnlist = ref_conversion(\@inlist, \%inhash);
The subroutine will have to dereference the arguments in order to access the data values they
represent.
Prototypes allow you to design your subroutines to take arguments with constraints on
the number of parameters and types of data.
Example 5.1:
sub Three {
return (1 + 2);
}
Any variables used in a subroutine that aren’t declared private are global variables. The my
function declares variables that are lexically scoped within the subroutine. This means that
they are private variables that only exist within the block or routine in which they are called.
The local function declares variables that are dynamic. This means that they have global
scope, but have temporary values within the subroutine. Most of the time, use my to localize
variables within a subroutine.
Example 5.2
72
}
# Variant of Three() which inits $x and $y with the array
#trick sub Three2 { my ($x, $y) = (1,
2);
return ($x + $y);
}
But if PERL can give you a new @_ for every invocation, can’t it give you variables
for your own use as well? Of course, it can. By default, all variables in PERL are
global variables; that is, they are accessible from every part of the program. But you
can create private variables called lexical variables at any time with my operator:
sub max {
These variables are private (or scoped) to the enclosing block; any other $m or $n is
totally unaffected by these two. And that goes the other way, too—no other code can
access or modify these private variables, by accident or design.
So, you could drop this subroutine into any PERL program in the world and know that
you wouldn’t mess up that program’s $m and $n (if any).
73
@_ Parameters
PERL subroutines do not have formal named parameters like other languages. Instead, all the
parameters are passed in a single array called "@_". The elements in @_ actually point to the
original caller-side parameters, so the called function is responsible for making any copies.
Usually the subroutine will pull the values out of @_ and copy them to local variables. A
Sum() function which takes two numbers and adds them as follows:
sub Sum1 { my ($x, $y) = @_; # the first lines of many #functions look like this to
retrieve and name their
#params return($x + $y);
}
# Variant where you pull the values out of @_ directly
# This avoids copying the parameters sub Sum2 {
return($_[0] + $_[1]);
}
# How Sum() would really be written in PERL -- it takes
#an array of numbers of arbitrary length, and adds all of
#them...
sub Sum3 { my ($sum, $elem); # declare local vars
$sum = 0; foreach $elem (@_)
{ $sum += $elem;
} return($sum);
74
5.1.4 Regular Expressions
PERL's most famous strength is in string manipulation with regular expressions. A regular
expression is a way of describing a class of similar strings in a very compact pattern notation.
In the simplest case, the exact characters in the regular expression pattern must occur in the
string somewhere. All of the characters in the pattern must be matched, but the pattern does
not need to be right at the start or end of the string, and the pattern does not need to use all the
characters in the string.
A whole regex is (usually) placed inside a pair of `/' signs. Variables are interpolated before
pattern-matching occurs.
"[email protected]" =~ m/^[\w._-]+@[\w._-]+$/
==> TRUE
75
5.1.6 Special Variables $1, $2, $3 …
If a =~ match expression is true, the special variables $1, $2, ... will be the substrings that
matched parts of the pattern in parenthesis -- $1 matches the first left parenthesis, $2 the
second left parenthesis, and so on. The following pattern picks out three words separated by
whitespace.
The following loop rips through a string and pulls out all the email addresses. It demonstrates
using a character class, using $1 etc. to pull out parts of the match string, and using $' after
the match.
} output:
Regular expressions, often abbreviated as regex or regexp, are sequences of characters that
define a search pattern. They are widely used in programming and text processing to match
and manipulate strings based on specific patterns.
76
5.1.7 Regular Expression Operators
There are three regular expression operators within PERL:
The match operator, m//, is used to match a string or statement to a regular expression.
Example: A string and regular expression is matched, on success it returns “match found”
otherwise “match not found”.
#!/usr/bin/PERL
# Initializing a string
$a = "University";
# matching the string and a regular expression and
# returns match found or not if ($a =~ m/Uni/)
{
print "Match Found\n";
} else { print "Match Not Found\n";
}
Output
Match Found
The substitution operator, s///, is a variation of the match operator that is used to search and
replace. The basic form of the operator is −
s/PATTERN/REPLACEMENT/;
The PATTERN is the regular expression for the text that we are looking for. The
REPLACEMENT is a specification for the text or regular expression that we want to use to
replace the found text with. For example
#/user/bin/PERL
77
# Initialising a string
$string =~ s/Adams/Sunday/;
Output
The translation, tr/// or y///, is used to replace all the occurrences of a character with a given
single character.
tr/SEARCHLIST/REPLACEMENTLIST/
y/SEARCHLIST/REPLACEMENTLIST/
The translation replaces all occurrences of the characters in SEARCHLIST with the
corresponding characters in REPLACEMENTLIST.
Example:
#/user/bin/PERL
# Initialising a string
$string = 'Universities';
$string =~ tr/s/z/;
Output
Univerzitiez
78
Standard PERL ranges can also be used, allowing you to specify ranges of characters either
by letter or numerical value.
$string =~ tr/a-z/A-Z/;
Parameters are variables defined within a subroutine or function that receive the values of the
arguments passed to the subroutine when it is called. They serve as placeholders for the input
values that will be used and manipulated within the subroutine.
$output = join($delimiter,@inlist);
79
Pilot Question 5.1
1. Write a simple PERl program to calculate the variable length, calculate the minimum
and maximum value.
Unit 5.2
Single character
A single printable character matches itself [set] matches any single character in the set e.g.
For example, [aeiou] matches any single lowercase vowel. Also, the set may contain items of
the form a-f, which is a shorthand for abcdef.
For example, [a-z#%] matches any single lower-case letter, a hash-mark, or a percent sign. If
a set starts with a `^' character (eg. [^a-z#%]), the set is negated - the pattern matches any
character NOT in the set.
Digit \d [0-9]
Non-digit \D [^0-9]
Words \w [a-zA-Z0-9_]
Non-word \W [^a-zA-Z0-9_]
Whitespace \s space or tab
Non-whitespace \S not space or tab
80
5.2.1 Grouping features
eg. /[a-z]bc/ matches any lower case letter, followed immediately by a `b', followed
immediately by a `c', anywhere in the string.
Optional: `?' makes the previous pattern optional - i.e. match zero or one times. eg. /he?llo/
matches `hello' or `hllo'.
Zero-or-more: `*' makes the previous pattern apply any number of times (from 0 upwards).
eg. /he*llo/ matches `hllo', `hello', `heello' etc. It consumes the maximum number of `e's
possible (it's greedy).
One-or-more: `+' means match 1 or more times. eg. /he+llo/ matches `hello', `heello', `heeello'
etc but not `hllo'.
A regex can contain several of these operators: eg: /h[uea]*l+o/ matches `hlo', `hullo',
`hulllllo', `heeelo', `heuaueaaeuelllllllo' etc.
One problem with * and +, is that they are "greedy" -- they try to use up as many characters
as they can. Suppose you are trying to pick out all of the characters between two curly braces
{ }.
The problem is that if you match against the string "{group 1} xx {group 2}", the * will
aggressively run right over the first } and match the second }. So $1 will be "group 1} xx
{group 2" instead of "group 1". Fortunately PERL has a nice solution to the too-aggressive-
*/+ problem. If a? immediately follows the * or +, then it tries to find the shortest repetition
which works instead of the longest. You need the ? variant most often when matching with .*
or \S* which can easily use up more than you had in mind. Use ".*?" to skip over stuff you
don't care about, but have something you do care about immediately to its right. Such as..
## at the first}
81
The old way to skip everything up until a certain character, say }, uses the [^}] construct like
this.
Placing `^' at the start of a regex matches the start of the string. Similarly, `$' at the end of a
regex matches the end of the string.
Brackets may be placed around any complete sub-pattern, as a way of enforcing a desired
precedence. For example, in /so+ng|bla+ckbird/ obviously bird is only part of (bla+ckbird).
Brackets have another useful side effect: they tell PERL's regex engine to remember or
capture the text fragment that matched the inner pattern for later reporting or reuse. eg:
After the match succeeds, the capture buffer variable $1 contains soooong - the part of $str
matching the bracketed regex.
82
5.2.4 RE special characters
RE examples
[qjk] # Either q or j or k
More examples
83
[^aeiou]+ # matches one or more nonvowels
\n # A newline
\t # A tab
\B # No word boundary
\| # Vertical bar
\) # A closing parenthesis
\* # An asterisk
\^ # A carat symbol
84
\/ # A slash
\\ # A backslash
# dadada or...
85
"piiig" =~ m/pi+g/ ==> TRUE
#### matches iii
"piiig" =~ m/i+/ ==> TRUE
"piiig" =~ m/p+i+g+/ ==> TRUE
"piiig" =~ m/p+g+/ ==> FALSE
#### i* = zero or more i's
"piiig" =~ m/pi*g/ ==> TRUE
"piiig" =~ m/p*i*g*/ ==> TRUE
#### X* can match zero X's
"piiig" =~ m/pi*X*g/ ==> TRUE
#### ^ = start, $ = end
"piiig" =~ m/^pi+g$/ ==> TRUE
#### i is not at the start
"piiig" =~ m/^i+g$/ ==> FALSE
#### i is not at the end
"piiig" =~ m/^pi+$/ ==> FALSE
"piiig" =~ m/^p.+g$/ ==> TRUE
"piiig" =~ m/^p.+$/ ==> TRUE
"piiig" =~ m/^.+$/ ==> TRUE
#### g is not at the start
"piiig" =~ m/^g.+$/ ==> FALSE
#### Needs at least one char after the g
"piiig" =~ m/g.+/ ==> FALSE
#### Needs at least zero chars after the g
"piiig" =~ m/g.*/ ==> TRUE
#### | = left or right expression
"cat" =~ m/^(cat|hat)$/ ==> TRUE
"hat" =~ m/^(cat|hat)$/ ==> TRUE
"cathatcatcat" =~ m/^(cat|hat)+$/ ==> TRUE
"cathatcatcat" =~ m/^(c|a|t|h)+$/ ==> TRUE
"cathatcatcat" =~ m/^(c|a|t)+$/ ==> FALSE
86
#### Matches and stops at first 'cat'; does not get to
'catcat' on the right
"cathatcatcat" =~ m/(c|a|t)+/ ==> TRUE
#### ? = optional
"12121x2121x2" =~ m/^(1x?2)+$/ ==> TRUE "aaaxbbbabaxbb" =~ m/^(a+x?b+)+$/ ==>
TRUE
"aaaxxbbb" =~ m/^(a+x?b+)+$/ ==> FALSE
#### Three words separated by spaces
"Easy does it" =~ m/^\w+\s+\w+\s+\w+$/ ==> TRUE
#### Just matches "gates@microsoft" -- \w does not match the
"."
"[email protected]" =~ m/\w+@\w+/ ==> TRUE
#### Add the .'s to get the whole thing
"[email protected]" =~ m/^(\w|\.)+@(\w|\.)+$/ ==> TRUE
#### words separated by commas and possibly spaces
"Klaatu, barada,nikto" =~ m/^\w+(,\s*\w+)*$/ ==> TRUE
5.2.6 Filehandles
Variables which represent files are called "file handles", and they are handled differently
from other variables. They do not begin with any special character -- they are just plain
words. By convention, file handle variables are written in all upper case, like FILE_OUT or
SOCK. The file handles are all in a global namespace, so you cannot allocate them locally
like other variables. File handles can be passed from one routine to another like strings. Every
PERL program has three filehandles that are automatically opened for it: STDIN, STDOUT,
and STDERR:
87
Box 5.7: Classes
Open files
File handles are created using the open() function:
open(FILE,”filename”);
As an aside, under Windows, there are a number of ways to refer to the full path to a file:
It is important to realize that calls to the open() function are not always successful. PERL will
not (necessarily) complain about using a filehandle created from a failed open(). This is why
we test the condition of the open statement:
Closing files
When you are finished using a filehandle, close it using close():
close(FILE);
88
Examples
$filename = “C:\\Documents\\”;
Delete file/Directory
Delete an existing file. Unlink can take a list of files, or wildcard as an argument as well:
unlink(<*.bak>)
unlink(filename)
Rename directory
89
This function renames a file. It is possible to move files into other directories by specifying a
path as part of the new name.
rename(oldname, newname)
mkdir(dirname, mode)
chdir(dirname)
Change the permissions of files/directories:
90
Summary for Study Session 5
In this study session 5, you have learnt that:
a. The simplest thing would be to use the pattern.
m/{(.*)}/ -- pick up all the characters between {}'s
The problem is that if you match against the string "{group 1} xx {group 2}", the * will
aggressively run right over the first } and match the second }. So $1 will be "group 1} xx
{group 2" instead of "group 1". Fortunately PERL has a nice solution to the too-aggressive-
*/+ problem. If a? immediately follows the * or +, then it tries to find the shortest repetition
which works instead of the longest. You need the ? variant most often when matching with .*
or \S* which can easily use up more than you had in mind. Use ".*?" to skip over stuff you
don't care about, but have something you do care about immediately to its right.
91
GLOSSARY OF TERMS
Subroutine: A subroutine is a named block of code within a program that performs a specific
task. It is designed to be reusable and can be called multiple times from different parts of the
program.
Argument: An argument refers to a value that is passed to a subroutine or function when it is
called. It provides input or data for the subroutine to work with. Arguments can be variables,
constants, expressions, or other data structures.
Parameters: Parameters are variables defined within a subroutine or function that receive the
values of the arguments passed to the subroutine when it is called. They serve as placeholders
for the input values that will be used and manipulated within the subroutine.
Regular Expressions: Regular expressions, often abbreviated as regex or regexp, are
sequences of characters that define a search pattern. They are widely used in programming
and text processing to match and manipulate strings based on specific patterns.
Classes: In object-oriented programming (OOP), a class is a blueprint or a template for
creating objects. It defines a set of attributes (data) and methods (functions) that describe the
behavior and characteristics of the objects that will be created based on the class.
Character: In programming, a character refers to a single element of a character set, such as
a letter, digit, symbol, or whitespace. Characters are the fundamental building blocks used to
represent textual information in programming languages.
Pattern: In programming, a pattern refers to a specific arrangement or sequence of characters
used to match or search for similar sequences in text or data. Patterns can be defined using
regular expressions or other specialized syntax.
92
Pilot Answers
# Array of variables
my @variables = (10, 5, 8, 3, 12);
2.
To stop a Perl subroutine program right away, you can use the return statement. The return
statement allows you to exit the subroutine and return to the calling code immediately
93
Pilot Answer 5.2
1.
In regular expressions, certain characters have special meanings and need to be escaped to
match them literally. Here's the definition of the following characters within regular
expressions:
\|: The backslash \ is used to escape the vertical bar | character in a regular expression.
Normally, | is a metacharacter that denotes alternation, meaning it matches either the
expression on its left or the expression on its right. However, by preceding it with a backslash
\|, it is treated as a literal character and matches the vertical bar character itself.
\[: The backslash \ is used to escape the opening square bracket [ character in a regular
expression. Square brackets are used to define character classes in regular expressions,
allowing you to specify a set of characters to match. By preceding the opening square bracket
with a backslash \[, it is treated as a literal character and matches the opening square bracket
itself.
\): The backslash \ is used to escape the closing parenthesis ) character in a regular
expression. Parentheses are used for grouping and capturing in regular expressions. By
preceding the closing parenthesis with a backslash \), it is treated as a literal character and
matches the closing parenthesis itself.
\*: The backslash \ is used to escape the asterisk * character in a regular expression. The
asterisk is a metacharacter that denotes zero or more occurrences of the preceding element.
By preceding the asterisk with a backslash \*, it is treated as a literal character and matches
the asterisk itself.
\^: The backslash \ is used to escape the caret ^ character in a regular expression. The caret
has multiple meanings in regular expressions, depending on its position. Inside square
brackets, it negates the character class. At the beginning of a pattern, it denotes the start of a
line. By preceding the caret with a backslash \^, it is treated as a literal character and matches
the caret itself.
\/: The forward slash / character does not need to be escaped in a regular expression, as it
does not have any special meaning. It can be used directly to match a forward slash character.
94
\\: The backslash \ is used to escape itself in a regular expression. By preceding the backslash
with another backslash \\, it is treated as a literal character and matches the backslash itself.
2.
The regular expressions mentioned in the previous message can be evaluated as follows:
"piiig" =~ m/g.+/ matches the string "piiig" against the pattern g.+.
Result: TRUE (The pattern matches "piiig" as it starts with 'g' and has one or more characters
after that.)
"cat" =~ m/^(cat|hat)$/ matches the string "cat" against the pattern ^(cat|hat)$
Result: TRUE (The pattern matches "cat" as it is either "cat" or "hat" according to the
provided alternatives within the parentheses.)
"hat" =~ m/^(cat|hat)$/ matches the string "hat" against the pattern ^(cat|hat)$
Result: TRUE (The pattern matches "hat" as it is either "cat" or "hat" according to the
provided alternatives within the parentheses.)
95
Self-Assessment Questions (SA Qs) for Study Session 5
1. Make a program that prints each line of its input that contains a period (.), ignoring
other lines of input. Try it on the small text file from the previous exercise: does it
notice Mr. Slate?
2. Make a program that prints each line that has a word that is capitalized but not ALL
capitalized. Does it match Fred but neither fred nor FRED?
3. Make a program that prints each line that has a two of the same non-whitespace
characters next to each other. It should match lines that contain words such as
Mississippi, Bamm-Bamm, or llama.
4. Write a subroutine, called &above_average, which takes a list of numbers and returns
the ones which are above the average (mean). (Hint: make another subroutine that
calculates the average by dividing the total by the number of items.) Try your
subroutine in this test program.
5. Write a subroutine named greet that welcomes the person you name by telling them
the name of the last person it greeted
greet (“Fred" );
greet (“Barney" );
This sequence of statements should print: Hi Fred! You are the first one here! Hi
Barney! Fred is also here!
6. Modify the previous program to tell each new person the names of all the people it
has previously greeted:
greet( "Fred" );
greet( "Barney" );
greet( "Wilma" );
greet( "Betty" );
96
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
97
Study Session 6
Content
Introduction
Learning Outcomes
Learning Activities
Unit 6.1: Modules and Database
6.1.1 Database and PERL
6.1.2 Database Drivers
6.1.3 PERL And Web Programming
6.1.4 Function-Oriented Script
Unit 6.2: Soap and Socket Programming
Summary for Study Session 6
Glossary of Terms
Pilot Answers
Self-Assessment Questions (SA Qs) for Study Session 6
References/Further Reading
98
Study Session 6: Operators and Control Statements
Introduction
Interacting with a database in PERL involves two pieces: the DBI and the database driver, or
DBD. Each of these pieces is a PERL module. The DBI provides the software interface that is
independent of the database, and the DBD provides the software that is database-dependent.
SOAP is a means by which remote procedures or methods can be called as if they were local.
99
Unit 6.1
$Package::varname
Modules allow you to split a large program into separate source files and namespaces,
controlling the interface. They extend the functionality of core PERL with additional
compiled code and scripts. To make use of a package (if it’s installed on your system), call
the use function:
use CGI;
This will pull in the module’s subroutines and variables at compile time. PERL looks for
modules by searching the directories listed in @INC. Modules can be obtained from the
Comprehensive
http://www.ActiveState.com/packages/zips/
To install modules under UNIX, unarchive the file containing the package, change into its
directory and type:
100
On Windows, the ActivePERL distribution makes use of the “PERL Package Manager” to
install/remove/update packages. To install a package, run ppm on the .ppd file associated
with the module:
Interacting with a database in PERL involves two pieces: the DBI and the database driver, or
DBD. Each of these pieces is a PERL module. The DBI provides the software interface that is
independent of the database, and the DBD provides the software that is database-dependent.
Box 6.1: Database
What is DBI?
The DBI
The DBI (database independent/database interface), contains data-access libraries that are
independent of the type of database. The DBI provides a generic interface on which you call
a driver to access a database. This general interface allows you to use some common
methods, regardless of the backend database. The DBI is a module in itself, and thus is called
into your program’s namespace with a use pragma:
use DBI;
The DBI loads one or more database drivers (generally referred to as DBD, for database
dependent). The DBD, which will be discussed shortly, has the specific software and code
required to access a given type of database. It provides the interface between the DBI and the
type of database for the connection. When coupled with the appropriate DBD, the DBI is the
key to making database connections work.
101
leaving the implementation-specific bits to the DBD. You might be curious as to which
drivers are installed on your server. The DBI module provides a function for listing all of the
currently installed drivers. The example below uses the available_drivers() function of the
DBI module to retrieve the drivers available on the server.
#!/usr/bin/PERL use
strict; use DBI; my
@drivers;
@drivers = DBI->available_drivers(); foreach my $dbd
(@drivers) { print "$dbd driver is available\n";
} exit;
You run this program from the command line. The output will look something like this:
The program incorporates the DBI into the namespace with this line:
use DBI;
The available drivers are placed into an array called @drivers with this line:
@drivers = DBI->available_drivers;
Finally, the array is expanded within the foreach loop and printed to STDOUT, producing the
output. From the output, it is seen that MySQL DBD is installed on this server. If you wanted
to connect to a different type of database, you would need to obtain the DBD module from
your favorite CPAN mirror or install it from your distribution’s repository. For example,
Debian 3.0 includes a number of DBDs, a listing of which is available by searching the
repository with the command apt-cache search dbd.
What are the lists of some of the more popular DBDs we have?
1. MySQL: As previously stated, MySQL is one quarter of the prized LAMP (Linux-
102
3. ODBC: The ODBC DBD is commonly used to connect to databases that run on
Windows systems, such as Microsoft SQL Server and Microsoft Access, but the
ODBC driver could be used to connect to virtually any database that offers ODBC
connectivity.
4. Sybase: Another popular DBD is used with the Sybase database server.
CGI
CGI (Common Gateway Interface) is a standard of communication between a web server and
a client, such as a user with a web browser. CGI is a class of programs that work with web
servers. The programs themselves are considered to be external or separate from the web
servers, but they provide a gateway between the client and server and it provides a common
interface i.e. the CGI programs can be written in a number of languages. Of the languages
with which a CGI program can be written, PERL is arguably the most common.
The function-oriented method of CGI development allows you to rapidly develop small CGI
scripts. The function-oriented method requires that the developer explicitly call or import the
desired functions into their program. This is sometimes done by importing the method groups
rather than the individual methods themselves. The most common method grouping in
practice is the :standard group. This method group contains the most frequently used
methods, including those that make it easy to create and use of web forms, as well as the
HTML that surrounds those forms.
103
use CGI ':standard'; print
header;
print start_html('Hello World'); print h1('Hello
World'); print end_html(); exit;
Create this code in you’re a text editor and save it to a location defined to run CGI scripts
within your web server. For example, you can save the script as hello.cgi in the directory
/usr/lib/cgibin. The CGI will need the correct permissions in order to run. This can usually be
accomplished with the chmod 755 <scriptname.cgi> command:
To view the code in a web browser, point the browser to the URL (uniform resource locator)
of the CGI script. For example, if the script is on a server at the IP address 192.168.1.10.
Combining the server address plus the aliased script location results in the following URL. If
all goes well, you should see a page similar to that in Figure below.
104
From the example, it is seen that the standard invocation of the PERL interpreter
#!/usr/bin/PERL.
#!/usr/bin/PERL
The next line of code enables strict checking for the script: use
strict;
This line will show up in every script in this chapter. Following use strict; is the code that
actually calls the CGI.pm module, and more specific module.
Four functions of the CGI module are used in this script, as shown here:
print header;
print start_html('Hello World'); print h1('Hello
World'); print end_html();
The first function, header(), sends the Content-Type to the browser. In this instance, the
header() function is equivalent to using this bit of code in the script:
The header() function can also be used for other HTTP headers, such as cookies. The next
CGI function used is start_html(). This function begins the HTML portion of the page with
elements like <title>, <html>, <head>, and so on. In this instance, the script calls the
start_html() function with a string parameter 'Hello World'. Another CGI function called in
this script is h1(). This function places an <h1> element around its parameter. In this case, the
parameter passed is 'Hello World', the phrase “Hello World” was indeed given <h1> size.
Finally, the end_html() function is called to provide the </body> and </html> closing tags.
The code in the example uses a semicolon (;) to end each line and then another print
statement to begin the next line. This was done to make the code easier to read. However, it’s
quite common to use a comma in place of the semicolon when programming a CGI
application, so the code would look like this:
105
h1('Hello World'),
end_html(); exit;
Unit 6.2
SOAP is a ubiquitous protocol for exchanging information on the Internet. SOAP is a means
by which remote procedures or methods can be called as if they were local. When you call a
SOAP (Simple Object Access Protocol) method, you are requesting an application to perform
some computation and return a result to your program. This is the same concept as a local
method call; it’s just that the SOAP call happens to be remote. These method calls sent using
SOAP can be transported over a number of mechanisms, such as over HTTP. SOAP provides
a well-formed means to obtain information from a data source. In a SOAP request, you
provide parameters as required by the receiving application. These parameters are then used
by the server, which executes the query to the application’s data source on behalf of the client
and returns values to the client in a SOAP response. This information can then be parsed and
used within the local PERL application. The PERL SOAP::Lite module can be used to create
a SOAP client and a SOAP listener.
SOAP (Simple Object Access Protocol). SOAP is a means by which remote procedures or
methods can be called as if they were local.
SOAP is client/server format, with one side sending the message and the other side parsing
the XML content of the message. The application may take action based on the results of the
message, either on the receiver or sender, or both. SOAP is an XML format with three
106
elements: envelope, header, and body. The SOAP header and SOAP body are both contained
within the
SOAP envelope. The SOAP header is actually optional, although it’s almost always included.
The SOAP body contains the heart of the SOAP message. Several popular web sites have
SOAP interfaces available lists a select few of these services, along with a short description
of each. Some website with SOAP interface
Amazon.com
National Weather Web services to http://weather.gov/xml/
expose forecasts and
Service
conditions based on
latitude and
longitude; available
for U.S. locations
Google Interfaces to query http://www.google.com/apis/
Google’s directory
and more
The socket is a medium through which two computers can interact on a network by using
network address and ports. To implement socket programing we need to create sockets in
both A(Server) and B (Client), A will be in the receiving state and B will be in the sending
state. The server wished to receive a connection from B(Client) and execute some tasks and
send the result back to B(Client). When we execute the code, the operation system in A tries
to create a socket and binds one port to that socket. Then it will listen from the sender which
is B. The client wishes to send some program from his system to A (Server) for some
processing. When we execute the code, the operating system in B tries to create a socket for
communicating with A (Server), B has to specify the IP address and the port number of A to
107
which B wishes to connect. If this goes well, both systems will interact to exchange the
information through one port. PERL also support socket programing. PERL has a native API
through which sockets can be implemented. To make it easy there are many CPAN modules
using which we write socket program. Server operations are:
1. Create socket
2. Bind socket with address and port
3. Listen to the socket on that port address
4. Accept the client connections which tries to connect using the port and IP of the
server
5. Perform operations
Box 6.4: Socket
The socket is a medium through which two computers can interact on a network by using
network address and ports.
Sockets PERL has full support for TCP/IP sockets, which means that you could write a web
server in PERL, or a web browser, Usenet news server or client, finger daemon or client, FTP
daemon or client, SMTP or POP or SOAP server or client, or either end of pretty much any
other kind of protocol in use on the Internet. You’ll find low-level modules for these in the
Net:: namespace, and many of them come with PERL.
Of course, there’s no need to get into the low-level details yourself; there are modules
available for all of the common protocols. For example, you can make a web server or client
with the LWP module and one or two lines of additional code.‖ The LWP module (actually, a
tightly integrated set of modules, which together implement nearly everything that happens
on the Web) is also a great example of high-quality PERL code, if you’d like to copy from
the best. For other protocols, search for a module with the protocol’s name.
Client Operations are:
1. Create Socket
2. Connect to Server using on its port address
108
Summary for Study Session 6
1. MySQL: As previously stated, MySQL is one quarter of the prized LAMP (Linux-
3. ODBC: The ODBC DBD is commonly used to connect to databases that run on
Windows systems, such as Microsoft SQL Server and Microsoft Access, but the
ODBC driver could be used to connect to virtually any database that offers ODBC
connectivity.
4. Sybase: Another popular DBD is used with the Sybase database server.
The SOAP header is actually optional, although it is almost always included. The SOAP body
contains the heart of the SOAP message. Several popular web sites have SOAP interfaces
available. Make a list of a few of these services, along with a short description of each. You
can also identify some websites with SOAP interface.
109
Pilot Answers
Pilot Answer 6.1
Perl is a programming language known for its versatility and flexibility in handling various
tasks, including working with databases. When it comes to databases, Perl offers several
features that contribute to its uniqueness:
Comprehensive Database Support: Perl provides comprehensive support for
connecting to and interacting with databases. It offers a wide range of database
modules and APIs (such as DBI, DBD::Oracle, DBD::MySQL, DBD::SQLite) that
allow Perl programs to connect to various database systems, including Oracle,
MySQL, SQLite, PostgreSQL, and more.
CPAN Modules: Perl's Comprehensive Perl Archive Network (CPAN) is a vast
repository of modules contributed by the Perl community. CPAN hosts numerous
modules specifically designed for database connectivity, query execution, and
database management. These modules provide ready-to-use functionalities, making it
easier to work with databases in Perl.
DBI (Database Interface): Perl's DBI module is a database-independent interface that
allows Perl programs to work with databases using a consistent API. It provides a
unified interface to connect to different database systems, execute queries, fetch
results, and manage transactions. DBI helps abstract the differences between database
systems, allowing developers to write portable database code.
Flexible Database Integration: Perl's syntax and flexibility make it well-suited for
integrating with databases. Perl offers powerful text manipulation capabilities, regular
expressions, and native support for handling data structures such as arrays and hashes.
This enables developers to efficiently process and manipulate database results,
transform data, and build complex data structures from query outputs.
Rapid Prototyping: Perl's concise and expressive syntax, combined with its database
integration capabilities, make it an excellent choice for rapid prototyping and scripting
tasks involving databases. Perl's ability to handle text processing, perform file I/O
operations, and interact with databases seamlessly makes it well-suited for tasks such
as data migration, data transformation, report generation, and automation of database-
related tasks.
110
Pilot Answer 6.2
1. Server operations refer to the various tasks and actions that can be performed on a
server. Here are some common server operations:
Starting and stopping the server: This involves initiating the server software or
shutting it down gracefully.
Configuring server settings: This includes modifying server configuration files to
customize the behavior and settings of the server.
Managing user accounts and access: Creating, modifying, or deleting user accounts
and managing their permissions and access levels on the server.
File management: Uploading, downloading, moving, copying, and deleting files and
directories on the server.
Installing and updating software: Installing new software applications or updating
existing ones on the server.
Monitoring server performance: Monitoring and analyzing server performance
metrics such as CPU usage, memory utilization, network traffic, etc.
Handling security measures: Implementing security protocols, managing firewalls,
configuring SSL certificates, and ensuring server security.
Handling backups and disaster recovery: Creating and managing backups of server
data to prevent data loss and implementing strategies for disaster recovery.
Troubleshooting and debugging: Identifying and resolving server-related issues,
errors, or malfunctions.
Managing network services: Configuring and managing various network services
such as DNS, DHCP, web server, email server, database server, etc.
2. SOAP is primarily used for communication and data exchange between web services,
while FTP is focused on file transfer between a client and a server. SOAP facilitates remote
procedure calls and structured data exchange, while FTP is designed specifically for file
management.
111
Self-Assessment Question (SAQs) for Study Session 6
1. State out the uniqueness of database in PERL programming language.
2. Write a simple function oriented script to calculate BMI of a named individual
3. List five websites, describe their information and URL.
112
References/Further Reading
www.cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf -
https://cs.fit.edu/~ryan/cse1002/lectures/introduction.pdf
113